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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值