Updated: May 15,2019
Now it comes as a surprise to many people when I tell them that generating an audio waveform is extremely simple.
One needs to have basic understanding on how audio signals work and basic python programming to generate any audio wave form. This post will show you exactly how.
Python packages needed: Numpy, Scipy
How to play the audio the generated audio file on computer ?
1. Command line using SoX
play -t raw -r 44.1k -e signed -b 8 -c 1 test.wav
where -r = sampling rate -b = sampling precision (bits) -c = number of channels
2. Use Audacity (check video)
Link to code : GitHub
You can find a list of other waveforms that can be generated using SciPy here
Known Issues:
[1] This does add any headers to the audio file and therefore you cannot play it on any media player as is . Check this reddit post if you really want to have one.
[2] Adding headers to the above code seems to be making it slower. And this is a problem if you want to make larger audio files.
[3] The code generates only 8-bit audio signal. Feel free to play around with the code to change it to other formats.
[4] A lot of technical details were conveniently not included in code in order to appeal to the theme of this post. And therefore this code is not “efficient”.
For writing audio files / sample data you might want to consider using the popular PySoundfile library: https://pysoundfile.readthedocs.io/
LikeLiked by 1 person
For improved file-writing, you don’t need to loop over all elements. Just do
y.astype(np.int8).tofile(‘test.wav’)
LikeLiked by 1 person
That’s awesome ! Thanks! π
LikeLike
The code shown here does not generate wav files.
The wav file format is not just a collection of samples. It is a collection of chunks of data. One of these chunks contains samples.
LikeLike
You are right Nicolas, it does not generate a wav file. But it does generate a raw audio data file which contains the information
LikeLike
Pingback: Import Python: import python weekly Issue No 130 – fast sudoku solver, colorama, ShutIt, audio analysis and more | Adrian Tudor Web Designer and Programmer
Pingback: Simple Wave Generation in Python (and SciPy) | Hackaday
Thanks, very useful article!
By the way, I guess number of samples should be equal Fs * t, where t is the duration of the audio track? On the screenshot you have “sample = 44100 / 440”.
LikeLike
is this related to digital communications and if it is…..please give the explanation?
LikeLike
Hy there,
I’m new to python and I have to do a project on a raspberry pi 2 – I hope you can help…
I need to record a 10 second audio file throug a electrek microphone at an mcp3008 which is cabled to the SPI interface on the raspberry pi.
Now I have values form 0 to 1023 but I don’t now how to transfer this into a wave file that I can play on the raspi…
Do you have any advices?
Thanks π
LikeLike