Python--讀取wav格式檔案__Python

來源:互聯網
上載者:User
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-8from Tkinter import *import waveimport matplotlib.pyplot as pltimport numpy as npdef read_wave_data(file_path):#open a wave file, and return a Wave_read objectf = wave.open(file_path,"rb")#read the wave's format infomation,and return a tupleparams = f.getparams()#get the infonchannels, sampwidth, framerate, nframes = params[:4]#Reads and returns nframes of audio, as a string of bytes. str_data = f.readframes(nframes)#close the streamf.close()#turn the wave's data to arraywave_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 datawave_data = wave_data.T#calculate the time bartime = np.arange(0, nframes) * (1.0/framerate)return wave_data, timedef main():wave_data, time = read_wave_data("C:\Users\CJP\Desktop\miss_you.wav")#draw the waveplt.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、效果


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.