Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get wav samples from a wav file?

Tags:

python

wav

I want to know how to get samples out of a .wav file in order to perform windowed join of two .wav files.

Can any one please tell how to do this?

like image 378
kaki Avatar asked Jun 17 '10 05:06

kaki


2 Answers

The wave module of the standard library is the key: after of course import wave at the top of your code, wave.open('the.wav', 'r') returns a "wave read" object from which you can read frames with the .readframes method, which returns a string of bytes which are the samples... in whatever format the wave file has them (you can determine the two parameters relevant to decomposing frames into samples with the .getnchannels method for the number of channels, and .getsampwidth for the number of bytes per sample).

The best way to turn the string of bytes into a sequence of numeric values is with the array module, and a type of (respectively) 'B', 'H', 'L' for 1, 2, 4 bytes per sample (on a 32-bit build of Python; you can use the itemsize value of your array object to double-check this). If you have different sample widths than array can provide you, you'll need to slice up the byte string (padding each little slice appropriately with bytes worth 0) and use the struct module instead (but that's clunkier and slower, so use array instead if you can).

like image 190
Alex Martelli Avatar answered Sep 27 '22 23:09

Alex Martelli


You can use the wave module. First you should read the metadata, such us sample size or the number of channels. Using the readframes() method, you can read samples, but only as a byte string. Based on the sample format, you have to convert them to samples using struct.unpack().

Alternatively, if you want the samples as an array of floating-point numbers, you can use SciPy's io.wavfile module.

like image 41
Lukáš Lalinský Avatar answered Sep 27 '22 22:09

Lukáš Lalinský