我目前正在尝试用Python生成声音,我很好奇我如何采用表示波形的n数组(采样率为44100 hz)并播放它。我在这里寻找纯Python,而不是依赖于支持多种.wav格式的库。
答案 0 :(得分:4)
您 应该 使用库。在纯python中编写所有内容可能需要数千行代码才能与音频硬件连接!
使用库,例如audiere,它将如此简单:
import audiere
ds = audiere.open_device()
os = ds.open_array(input_array, 44100)
os.play()
还有pyglet,pygame和许多其他..
答案 1 :(得分:4)
播放16位采样数组 input_array 的声音。这是pyadio documentation page
的修改示例import pyaudio
# instantiate PyAudio (1)
p = pyaudio.PyAudio()
# open stream (2), 2 is size in bytes of int16
stream = p.open(format=p.get_format_from_width(2),
channels=1,
rate=44100,
output=True)
# play stream (3), blocking call
stream.write(input_array)
# stop stream (4)
stream.stop_stream()
stream.close()
# close PyAudio (5)
p.terminate()
答案 2 :(得分:4)
或使用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)
答案 3 :(得分:3)
我想你可能看一下这个清单 http://wiki.python.org/moin/PythonInMusic 它列出了许多用于处理声音的有用工具。
答案 4 :(得分:0)
这是摘自this stackoverflow answer的一小段代码,还有一个播放numpy数组(已载入scipy的声音文件)的示例:
from wave import open as waveOpen
from ossaudiodev import open as ossOpen
from ossaudiodev import AFMT_S16_NE
import numpy as np
from scipy.io import wavfile
# from https://stackoverflow.com/questions/307305/play-a-sound-with-python/311634#311634
# run this: sudo modprobe snd-pcm-oss
s = waveOpen('example.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
print(nc,sw,fr,nf,comptype, compname)
_, snp = wavfile.read('example.wav')
print(snp)
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(snp.tobytes())
dsp.write(data)
dsp.close()
基本上,您可以只调用tobytes()方法;然后可以播放返回的字节数组。
P.S。这种方法非常快速