How to generate audio from a numpy array?


I want to create "heart rate monitor" effect from a 2D array in numpy and want the tone to reflect the values in the array.

4/28/2012 4:21:54 PM

Accepted Answer

You can use the write function from to create a wav file which you can then play however you wish. Note that the array must be integers, so if you have floats, you might want to scale them appropriately:

import numpy as np
from import write

data = np.random.uniform(-1,1,44100) # 44100 random samples between -1 and 1
scaled = np.int16(data/np.max(np.abs(data)) * 32767)
write('test.wav', 44100, scaled)

If you want Python to actually play audio, then this page provides an overview of some of the packages/modules.

12/16/2012 2:27:10 PM

For the people coming here in 2016 scikits.audiolab doesn't really seem to work anymore. I was able to get a solution using sounddevice.

import numpy as np
import sounddevice as sd

fs = 44100
data = np.random.uniform(-1, 1, fs), fs)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow