Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing a sound from a wave form stored in an array

Tags:

python

wav

I'm currently experimenting with generating sounds in Python, and I'm curious how I can take a n array representing a waveform (with a sample rate of 44100 hz), and play it. I'm looking for pure Python here, rather than relying on a library that supports more than just .wav format.

like image 625
Jordan Scales Avatar asked Jan 03 '12 04:01

Jordan Scales


People also ask

What is a wave form in audio?

Term: Waveform (sound) The generic term waveform means a graphical representation of the shape and form of a signal moving in a gaseous, liquid, or solid medium. For sound, the term describes a depiction of the pattern of sound pressure variation (or amplitude) in the time domain.


2 Answers

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)
like image 87
mjp Avatar answered Nov 14 '22 11:11

mjp


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.

like image 20
wim Avatar answered Nov 14 '22 09:11

wim