2012-01-03 32 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