python分析pcm音频文件

最近研究的,我用的是python3.3, 用matplotlib画图,

下面代码演示分析pcm文件,如果是wave文件,把wave的文件头去掉就是pcm文件了。

代码如下

# -*- coding:utf-8 -*-

import array
import os
from matplotlib import pyplot

fileName = 'e:/music/qianqian.pcm' # 2 channel, 16 bit per sample
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]

def showPCM(leftChannel, rightChannel, 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)

 

python分析pcm音频文件_第1张图片

 

python分析pcm音频文件_第2张图片

另一种分析方法,用struct.unpack,但读取要比上一种慢很多

 

# -*- coding:utf-8 -*-

import struct
from matplotlib import pyplot

file = open('e:/music/qianqian.pcm', 'rb') # if file is too large, pyplot may overflow
count = 0
total = 0
base = 1 / (1<<15)
maxl = 0
minl = 0
maxr = 0
minr = 0
larray = []
rarray = []
# file has two channels, 16 bit per sample
while True:
    lr = file.read(4)
    if len(lr) < 4:
        break
    count += 1
    lvalue = struct.unpack('h', lr[:2])[0] * base
    larray.append(lvalue)
    if lvalue > maxl:
        maxl = lvalue
    if lvalue < minl:
        minl = lvalue
    total += lvalue
    rvalue = struct.unpack('h', lr[2:])[0] * base
    rarray.append(rvalue)
    if rvalue > maxr:
        maxr = rvalue
    if rvalue < minr:
        minr = rvalue

file.close()
avarage = total / count
print(count, total, avarage)
print('max = {0} min = {1}'.format(maxl, minl))

fig = pyplot.figure(1)
pyplot.subplot(211)
pyplot.title('pcm left channel')
pyplot.plot(range(count), larray)
pyplot.subplot(212)
pyplot.title('pcm right channel')
pyplot.plot(range(count), rarray)
pyplot.show()
# fig.savefig('pcm.pdf')

 

你可能感兴趣的:(音频)