2012-01-03 94 views
6

我目前正在用Python生成声音,并且我很好奇我如何获取表示波形的数组(采样率为44100赫兹),以及播放。我在这里寻找纯Python,而不是依赖一个支持的不仅仅是.wav格式的库。从存储在数组中的波形播放声音

回答

5

应该使用库。用纯python编写代码可能需要数千行代码,才能与音频硬件接口!

使用库(例如, audiere,这将是如此简单:

import audiere 
ds = audiere.open_device() 
os = ds.open_array(input_array, 44100) 
os.play() 

有也pyglet,pygame的,和许多其他..

+0

'audiere'似乎是一个很老的项目...最后发布于2006年,自述文件的Python绑定日期为2002年,并引用Python 2.2 ... – 2012-01-03 05:00:44

+0

我已经使用它自己在python 2.7上,它仍然工作正常。 audiere模块来自http://pyaudiere.org/,可能您正在查看http://audiere.sourceforge.net/。 pyaudiere使用Audiere API – wim 2012-01-03 05:17:34

+0

pyaudiere网站不再存在,audiere自2006年以来尚未更新。这不再是一个好的答案。 – jozzas 2012-04-05 00:24:08

3

播放声音给定的阵列input_array的16位采样。这是从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

变形例或使用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) 
+0

请注意,如果在Eclipse中运行,sounddevice不起作用。 – 2017-12-14 12:19:20