Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 857
gisgyaan Avatar asked Apr 27 '12 21:04

gisgyaan


4 Answers

You can use the write function from scipy.io.wavfile 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 scipy.io.wavfile import write

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

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

like image 70
huon Avatar answered Oct 25 '22 06:10

huon


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)
sd.play(data, fs)
like image 25
mdornfe1 Avatar answered Oct 25 '22 07:10

mdornfe1


in Jupyter the best option is:

from IPython.display import Audio
wave_audio = numpy.sin(numpy.linspace(0, 3000, 20000))
Audio(wave_audio, rate=20000)
like image 33
Alleo Avatar answered Oct 25 '22 06:10

Alleo


In addition, you could try scikits.audiolab. It features file IO and the ability to 'play' arrays. Arrays don't have to be integers. To mimick dbaupp's example:

import numpy as np
import scikits.audiolab

data = np.random.uniform(-1,1,44100)
# write array to file:
scikits.audiolab.wavwrite(data, 'test.wav', fs=44100, enc='pcm16')
# play the array:
scikits.audiolab.play(data, fs=44100)
like image 16
mwv Avatar answered Oct 25 '22 06:10

mwv