我目前正在尝试用Python生成声音,我很好奇如何使用表示波形的数组(采样率为44100 hz)并播放它.我在这里寻找纯Python,而不是依赖于支持多种.wav格式的库.
你应该使用图书馆。用纯 python 编写它可能需要数千行代码,以与音频硬件接口!
使用库,例如 audiere,它会像这样简单:
import audiere
ds = audiere.open_device()
os = ds.open_array(input_array, 44100)
os.play()
Run Code Online (Sandbox Code Playgroud)
还有 pyglet、pygame 等等。
编辑: audiere上面提到的模块似乎不再维护,但我对依赖库的建议保持不变。在此处选择当前项目:
https://wiki.python.org/moin/Audio/
https://pythonbasics.org/python-play-sound/
这里没有很多高级标准库“包含电池”的原因是因为与音频硬件的交互可能非常依赖于平台。
或使用声音设备模块。使用安装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)
Run Code Online (Sandbox Code Playgroud)
其他一些选择:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6426 次 |
| 最近记录: |