chanwcom
chanwcom

Reputation: 4650

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?

Upvotes: 3

Views: 3322

Answers (2)

bhaskarc
bhaskarc

Reputation: 9521

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.

Upvotes: 1

P. Camilleri
P. Camilleri

Reputation: 13218

I am not sure whether there exists a numpy function to do this, but you can convert your array (provided it only contains integers) to a wav file using this function from scipy.io.wavfile, and then play the file.

I have not gotten into the details, but I think this page references useful tools for sound in Python.

Edit: see also the answers to this SO question

Upvotes: 0

Related Questions