参考文章:
音频文件基本处理流程
Python中的音频和数字信号处理(DSP)
代码
最终生成test.wav文件
import numpy as np
import wave
import struct
import matplotlib.pyplot as plt
# frequency is the number of times a wave repeats a second
# 频率
frequency = 1000
# 音频长度
num_samples = 480000
# The sampling rate of the analog to digital convert
# 采样率
sampling_rate = 48000.0
# 振幅 32000对应1,即0db
amplitude = 24000
file = "test.wav"
sine_wave = [np.sin(2 * np.pi * frequency * x/sampling_rate) for x in range(num_samples)]
nframes=num_samples
comptype="NONE"
compname="not compressed"
# 通道数
nchannels=1
# 采样位宽
sampwidth=2
wav_file=wave.open(file, 'w')
wav_file.setparams((nchannels, sampwidth, int(sampling_rate), nframes, comptype, compname))
for s in sine_wave:
wav_file.writeframes(struct.pack('h', int(s*amplitude)))
注意amplitude 参数,当它为32000时,显示的波形的纵坐标峰值为1,对应的是1khz0db