Playing a sound from a wave form stored in an array

or use the sounddevice module. Install using pip install sounddevice, but you need this first: sudo apt-get install libportaudio2

absolute basic:

import numpy as np
import sounddevice as sd

sd.play(myarray) 
#may need to be normalised like in below example
#myarray must be a numpy array. If not, convert with np.array(myarray)

A few more options:

import numpy as np
import sounddevice as sd

#variables
samplfreq = 100   #the sampling frequency of your data (mine=100Hz, yours=44100)
factor = 10       #incr./decr frequency (speed up / slow down by a factor) (normal speed = 1)

#data
print('..interpolating data')
arr = myarray

#normalise the data to between -1 and 1. If your data wasn't/isn't normalised it will be very noisy when played here
sd.play( arr / np.max(np.abs(arr)), samplfreq*factor)

You should use a library. Writing it all in pure python could be many thousands of lines of code, to interface with the audio hardware!

With a library, e.g. audiere, it will be as simple as this:

import audiere
ds = audiere.open_device()
os = ds.open_array(input_array, 44100)
os.play()

There's also pyglet, pygame, and many others..


Edit: audiere module mentioned above appears no longer maintained, but my advice to rely on a library stays the same. Take your pick of a current project here:

https://wiki.python.org/moin/Audio/

https://pythonbasics.org/python-play-sound/

The reason there's not many high-level stdlib "batteries included" here is because interactions with the audio hardware can be very platform-dependent.

Tags:

Python

Wav