Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: write a wav file into numpy float array

Tags:

python

numpy

wav

ifile = wave.open("input.wav")

how can I write this file into a numpy float array now?

like image 708
IAM Avatar asked May 27 '13 18:05

IAM


3 Answers

>>> from scipy.io.wavfile import read
>>> a = read("adios.wav")
>>> numpy.array(a[1],dtype=float)
array([ 128.,  128.,  128., ...,  128.,  128.,  128.])

Typically it would be bytes which are then ints... here we just convert it to float type.

You can read about read here: https://docs.scipy.org/doc/scipy/reference/tutorial/io.html#module-scipy.io.wavfile

like image 175
Joran Beasley Avatar answered Nov 08 '22 20:11

Joran Beasley


Seven years after the question was asked...

import wave
import numpy

# Read file to get buffer                                                                                               
ifile = wave.open("input.wav")
samples = ifile.getnframes()
audio = ifile.readframes(samples)

# Convert buffer to float32 using NumPy                                                                                 
audio_as_np_int16 = numpy.frombuffer(audio, dtype=numpy.int16)
audio_as_np_float32 = audio_as_np_int16.astype(numpy.float32)

# Normalise float32 array so that values are between -1.0 and +1.0                                                      
max_int16 = 2**15
audio_normalised = audio_as_np_float32 / max_int16
like image 17
Matthew Walker Avatar answered Nov 08 '22 20:11

Matthew Walker


Use librosa package and simply load wav file to numpy array with:

y, sr = librosa.load(filename)

loads and decodes the audio as a time series y, represented as a one-dimensional NumPy floating point array. The variable sr contains the sampling rate of y, that is, the number of samples per second of audio. By default, all audio is mixed to mono and resampled to 22050 Hz at load time. This behavior can be overridden by supplying additional arguments to librosa.load().

More information at Librosa library documentation

like image 6
Esterlinkof Avatar answered Nov 08 '22 21:11

Esterlinkof