Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play sound from samples contained in NumPy array?

I'm trying to find a function which corresponds to soundsc() and sound() in Matlab. Basically, I'd like to listen to sound by playing samples contained in NumPy array. Are there some functions for doing this?

like image 705
chanwcom Avatar asked Dec 05 '25 03:12

chanwcom


1 Answers

This pertains to Linux & Mac

Most of Linux computers come pre-installed with vox library which let's you play audio from the command line.

So assume you write an array to wave file using scipy.io.write, you can play it from within Python program using the subprocess module.

Here's a complete example:

from scipy.io.wavfile import write
import numpy as np


fs = 44100 # sampling frequency
input_array = np.random.rand(fs*2) # 2 seconds audio
write('output.wav', fs, input_array)

# now that file is written to the disk - play it
import subprocess
subprocess.call(["play", 'output.wav']) <-  for linux
subprocess.call(["afplay", 'output.wav']) <- for Mac

For Windows, as far as I know there are no built-in command line players - so you may need to install some program that lets you do so before using the above code.

like image 151
bhaskarc Avatar answered Dec 08 '25 03:12

bhaskarc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!