最近研究的,我用的是python3.3, 用matplotlib画图,
下面代码演示分析pcm文件,如果是wave文件,把wave的文件头去掉就是pcm文件了。
代码如下
1 # -*- coding:utf-8 -*- 2 3 import array 4 import os 5 from matplotlib import pyplot 6 7 fileName = 'e:/music/qianqian.pcm' # 2 channel, 16 bit per sample 8 file = open(fileName, 'rb') 9 base = 1 / (1<<15)10 11 shortArray = array.array('h') # int1612 size = int(os.path.getsize(fileName) / shortArray.itemsize)13 count = int(size / 2)14 shortArray.fromfile(file, size) # faster than struct.unpack15 file.close()16 leftChannel = shortArray[::2]17 rightChannel = shortArray[1::2]18 19 def showPCM(leftChannel, rightChannel, start = 0, end = 5000):20 fig = pyplot.figure(1)21 22 pyplot.subplot(211)23 pyplot.title('pcm left channel [{0}-{1}] max[{2}]'.format(start, end, count))24 pyplot.plot(range(start, end), leftChannel[start:end])25 26 pyplot.subplot(212)27 pyplot.title('pcm right channel [{0}-{1}] max[{2}]'.format(start, end, count))28 pyplot.plot(range(start, end), rightChannel[start:end])29 30 pyplot.show()31 # fig.savefig('pcm.pdf') # save figure to pdf file32 33 showPCM(leftChannel, rightChannel, 0, count)
另一种分析方法,用struct.unpack,但读取要比上一种慢很多
1 # -*- coding:utf-8 -*- 2 3 import struct 4 from matplotlib import pyplot 5 6 file = open('e:/music/qianqian.pcm', 'rb') # if file is too large, pyplot may overflow 7 count = 0 8 total = 0 9 base = 1 / (1<<15)10 maxl = 011 minl = 012 maxr = 013 minr = 014 larray = []15 rarray = []16 # file has two channels, 16 bit per sample17 while True:18 lr = file.read(4)19 if len(lr) < 4:20 break21 count += 122 lvalue = struct.unpack('h', lr[:2])[0] * base23 larray.append(lvalue)24 if lvalue > maxl:25 maxl = lvalue26 if lvalue < minl:27 minl = lvalue28 total += lvalue29 rvalue = struct.unpack('h', lr[2:])[0] * base30 rarray.append(rvalue)31 if rvalue > maxr:32 maxr = rvalue33 if rvalue < minr:34 minr = rvalue35 36 file.close()37 avarage = total / count38 print(count, total, avarage)39 print('max = {0} min = {1}'.format(maxl, minl))40 41 fig = pyplot.figure(1)42 pyplot.subplot(211)43 pyplot.title('pcm left channel')44 pyplot.plot(range(count), larray)45 pyplot.subplot(212)46 pyplot.title('pcm right channel')47 pyplot.plot(range(count), rarray)48 pyplot.show()49 # fig.savefig('pcm.pdf')
代码及pcm下载:
下面这个地址也有一个例子:可以看看。