Python制作任意音频文件
程序员文章站
2022-05-04 14:07:52
...
本文件示例了如何用python脚本来生成任意波形的Wav音频文件,用来做为声音源帮助听力产品的测试。
python中需要安装wave、nump、scipy库;
下面为一生成无声音的脚本:
import wave
import numpy as np
import scipy.signal as signal
# sample frequency, unit = hz
frameRate = 16000
time = 60 # unit = second
volumn = 0 # 30000,音量设置
# 通过调用 scipy.signal库中的 chrip 函数,产生长度为10秒、取样频率为44.1kHz、100Hz到1kHz的频率扫描波
t = np.arange(0, time, 1.0 / frameRate)
#
# Save time line into xls file.
#
'''
ft = open("ti.xls", "w")
for item in t:
ft.write(str(item)+'\n')
ft.close()
'''
# chirp(t,f0,t1,f1,method='linear', phi=0, vertex_zero=True)
# t = array of time
# f0 = start frequency from t[0]
# t1 = end time
# f1 = frequency of t1
# for linear method: f(t) = f0 + (f1 - f0) * t/t1
wave_data = signal.chirp(t, 100, time, 100, method='linear') * volumn
# 由于chrip函数返回的数组为float64型,需要调用数组的astype方法将其转换为short型。
wave_data = wave_data.astype(np.short)
#
# Save time line into xls file.
#
maxVal = 0
minVal = 32768
fwave = open("wave.xls", "w")
for item in wave_data:
fwave.write(str(item)+'\n')
if maxVal < item:
maxVal = item
if minVal > item:
minVal = item
fwave.close()
print('[min,max] value=[' + str(minVal) + ',' + str(maxVal) + ']' )
'''
#data = 2+np.sin(np.random.rand(160000)) # random noise
data = 2+np.sin(np.array(range(160000))) # sin wave sound
data = data*10000 # increase volumn
data = data.astype(np.short) # convert wave dat to int16 from float64
print(type(data[0]))
# print(len(data))
# print(data[:3])
'''
f = wave.open(r"000.wav", "wb")
# 配置声道数、量化位数和取样频率
f.setnchannels(1) # 声道数
f.setsampwidth(2) # 量化位数
f.setframerate(frameRate) # 采样频率
f.writeframes(wave_data.tostring()) # 将wav_data转换为二进制数据写入文件
f.close()
上一篇: JedisPool工具类
下一篇: 设计模式学习之访问者模式