入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Python--读取wav格式文件

创建时间:2013-05-17 投稿人: 浏览次数:93
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:UsersCJPDesktopmiss_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、效果


声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。