从数组中播放存储的波形声音
我现在正在尝试用Python生成声音,我想知道怎么把一个表示波形的数组(采样率为44100赫兹)播放出来。我希望用纯Python来实现,而不是依赖一个只支持.wav格式的库。
5 个回答
4
我觉得你可以看看这个列表:http://wiki.python.org/moin/PythonInMusic。这个列表里有很多有用的工具,可以帮助你处理声音。
11
或者使用 sounddevice 这个模块。你可以通过 pip install sounddevice
来安装它,但在这之前你需要先运行这个命令:sudo apt-get install libportaudio2
最基本的用法:
import numpy as np
import sounddevice as sd
sd.play(myarray)
#may need to be normalised like in below example
#myarray must be a numpy array. If not, convert with np.array(myarray)
还有一些其他的选项:
import numpy as np
import sounddevice as sd
#variables
samplfreq = 100 #the sampling frequency of your data (mine=100Hz, yours=44100)
factor = 10 #incr./decr frequency (speed up / slow down by a factor) (normal speed = 1)
#data
print('..interpolating data')
arr = myarray
#normalise the data to between -1 and 1. If your data wasn't/isn't normalised it will be very noisy when played here
sd.play( arr / np.max(np.abs(arr)), samplfreq*factor)
6
你应该使用一个库。要用纯Python来写所有代码,可能会需要几千行代码才能和音频硬件对接!
使用一个库,比如说audiere,事情就简单多了,代码可能就像这样:
import audiere
ds = audiere.open_device()
os = ds.open_array(input_array, 44100)
os.play()
还有pyglet、pygame等等其他库可供选择。
编辑:上面提到的
https://wiki.python.org/moin/Audio/
https://pythonbasics.org/python-play-sound/
之所以没有很多高层次的标准库“自带电池”,是因为与音频硬件的交互可能会非常依赖于平台。