1、安装依赖
代码语言:javascript复制pip install pyaudio
pip install pylab
2、语音数据展示
代码语言:javascript复制import pyaudio
import numpy as np
CHUNK = 4096 # 每次采集的数据点数
RATE = 44100 # 采样频率
p=pyaudio.PyAudio() # 启动类
stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
frames_per_buffer=CHUNK) #输入设备
# 创建一个numpy来保存每次采集的数据
for i in range(10): #
data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
print(data)
# 关闭音频采集流
stream.stop_stream()
stream.close()
p.terminate()
3、声音波形可视化
首先采集数据,然后保存为图片,新建一个网页,在网页上展示波形图
代码语言:javascript复制import pyaudio
import numpy as np
import pylab
import time
RATE = 44100
CHUNK = int(RATE/20)
def soundplot(stream):
t1=time.time()
data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
pylab.plot(data)
pylab.title(i)
pylab.grid()
pylab.axis([0,len(data),-2**16/2,2**16/2])
pylab.savefig("03.png",dpi=50)
pylab.close('all')
print("took %.02f ms"%((time.time()-t1)*1000))
if __name__=="__main__":
p=pyaudio.PyAudio()
stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
frames_per_buffer=CHUNK)
for i in range(int(20*RATE/CHUNK)): #持续10s
soundplot(stream)
stream.stop_stream()
stream.close()
p.terminate()
网页代码
代码语言:javascript复制<html>
<script language="javascript">
function RefreshImage(){
document.pic0.src="03.png?a=" String(Math.random()*99999999);
setTimeout('RefreshImage()',50);
}
</script>
<body onload="RefreshImage()">
<img name="pic0" src="03.png">
</body>
</html>
效果如图