以下是使用Python读取音频文件并生成波形的代码示例:

import wave
import numpy as np
import matplotlib.pyplot as plt

# 读取音频文件
audio_file = wave.open('audio.wav', 'r')

# 获取音频文件的属性
nchannels = audio_file.getnchannels()
sampwidth = audio_file.getsampwidth()
framerate = audio_file.getframerate()
nframes = audio_file.getnframes()

# 读取音频数据
audio_data = audio_file.readframes(nframes)
audio_file.close()

# 将音频数据转换为numpy数组
audio_data = np.frombuffer(audio_data, dtype=np.int16)

# 根据声道数和采样位数重新排列音频数据
audio_data = audio_data.reshape(-1, nchannels)
audio_data = audio_data.astype(np.float32) / 32768  # 归一化

# 绘制波形图
plt.plot(audio_data)
plt.xlabel('Time (samples)')
plt.ylabel('Amplitude')
plt.show()

注意,此示例代码仅适用于单声道或双声道、16位采样率的音频文件。如果您的音频文件具有不同的属性,请相应地更改代码。

Python 音频波形生成代码:读取音频文件并可视化

原文地址: https://www.cveoy.top/t/topic/nqD5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录