在Python中播放向量聲音算芯。
需要的庫有:
在終端使用conda安裝:
conda install -c anaconda numpy
conda install -c anaconda pyaudio
代碼如下:
#引入庫
import numpy as np
import pyaudio
#定義播放函數(shù)和輸入數(shù)據(jù)
def play(sound,FS):
#sound 為輸入的聲音數(shù)據(jù),格式為向量或數(shù)列呢堰,F(xiàn)S為采樣頻率
????CHUNK=1024 #Samples per Blocksize,數(shù)據(jù)流塊大小
????WIDTH=2 #2 Bytes per Sample,每個采樣的大小
????CHANNELS=1 #Channels,聲道數(shù)量
????RATE = FS? #Sampling Rate in Hz,采樣頻率
????p = pyaudio.PyAudio()?
? ? #打開并定義數(shù)據(jù)流格式
????stream = p.open(format=p.get_format_from_width(WIDTH),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? channels=CHANNELS,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? rate=RATE,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? input=False,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? output=True,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? frames_per_buffer=CHUNK)
? ? for i in range(0, int(len(sound) / CHUNK) ):
? ? ? ? #把sound文件中的正數(shù)量化成比特
? ? ????samples=sound[i*CHUNK:((i+1)*CHUNK)];
? ? ? ? samples=clip(samples,-2**15,2**15-1)
? ? ? ? #播放
? ? ? ? stream.write(samples.astype(np.int16),len(samples))
? ? #播放完成隔躲,停止數(shù)據(jù)流
? ? stream.stop_stream()
? ? stream.close()