当前位置:   article > 正文

python播放PCM 音频文件_pcm播放

pcm播放

一:pyaudio安装

Ctrl+R输入cmd打开控制台执行如下命令

pip install PyAudio
  • 1

二: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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

三:Python分析PCM音频文件

安装画图模块

pip install matplotlib 
  • 1

分析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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/779125
推荐阅读
相关标签
  

闽ICP备14008679号