python播放PCM 音频文件
一:pyaudio安装
Ctrl+R输入cmd打开控制台执行如下命令
pip install PyAudio
二:Python播放PCM音频文件
import pyaudio
def PlayPCM():
# 初始化播放器
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2), channels=1, rate=16000, output=True)
file1 = "D:\\byby_8K_1C_16bit_agc.pcm";
# 将 pcm 数据直接写入 PyAudio 的数据流
with open(file1 , "rb") as f:
stream.write(f.read())
stream.stop_stream()
stream.close()
p.terminate()
PlayPCM()
三:Python分析PCM音频文件
安装画图模块
pip install matplotlib
分析pcm
import array
import os
from matplotlib import pyplot
def AnalizePCM(fileName):
file = open(fileName, 'rb')
base = 1 / (1<<15)
shortArray = array.array('h') # int16
size = int(os.path.getsize(fileName) / shortArray.itemsize)
count = int(size / 2)
shortArray.fromfile(file, size) # faster than struct.unpack
file.close()
leftChannel = shortArray[::2]
rightChannel = shortArray[1::2]
#分析
start = 0
end = 5000
fig = pyplot.figure(1)
pyplot.subplot(211)
pyplot.title('pcm left channel [{0}-{1}] max[{2}]'.format(start, end, count))
pyplot.plot(range(start, end), leftChannel[start:end])
pyplot.subplot(212)
pyplot.title('pcm right channel [{0}-{1}] max[{2}]'.format(start, end, count))
pyplot.plot(range(start, end), rightChannel[start:end])
pyplot.show()
# fig.savefig('pcm.pdf') # save figure to pdf file
showPCM(leftChannel, rightChannel, 0, count)
fileName1 = 'D:\\speaker.pcm'
AnalizePCM(fileName1)