Python 读取wav格式文件

1、import wave 用于读写wav文件
它提供了一个方便的WAV格式接口。
但是不支持压缩/解压缩,支持单声道/立体声。
读取格式:
open(file[, mode])
如果file是一个字符串,那么就打开文件,不然就把它当做一个类文件对象。
mode是可以缺省的,如果输入的参数是一个类文件对象,那么file.mode将会作为mode的值。
mode可选参数如下:
'r', 'rb'

Read only mode.

'w', 'wb'

Write only mode.

注意不能同时完成读/写操作

2、wav文件读操作

3、numpy:shape改变数组形状

当某数轴的参数为-1时,根据元素个数,自动计算此轴的最大长度,入将c数组改成2行

4、实例代码

#!usr/bin/env python
#coding=utf-8
 
from Tkinter import *
import wave
import matplotlib.pyplot as plt
import numpy as np
 
def read_wave_data(file_path):
	#open a wave file, and return a Wave_read object
	f = wave.open(file_path,"rb")
	#read the wave's format infomation,and return a tuple
	params = f.getparams()
	#get the info
	nchannels, sampwidth, framerate, nframes = params[:4]
	#Reads and returns nframes of audio, as a string of bytes. 
	str_data = f.readframes(nframes)
	#close the stream
	f.close()
	#turn the wave's data to array
	wave_data = np.fromstring(str_data, dtype = np.short)
	#for the data is stereo,and format is LRLRLR...
	#shape the array to n*2(-1 means fit the y coordinate)
	wave_data.shape = -1, 2
	#transpose the data
	wave_data = wave_data.T
	#calculate the time bar
	time = np.arange(0, nframes) * (1.0/framerate)
	return wave_data, time
 
def main():
	wave_data, time = read_wave_data("C:\Users\CJP\Desktop\miss_you.wav")	
	#draw the wave
	plt.subplot(211)
	plt.plot(time, wave_data[0])
	plt.subplot(212)
	plt.plot(time, wave_data[1], c = "g")
	plt.show()
 
if __name__ == "__main__":
	main()

5、效果

猜你喜欢

转载自blog.csdn.net/y_f_raquelle/article/details/84134990