Skip to content

Instantly share code, notes, and snippets.

@akey7
Created March 31, 2018 06:13
Show Gist options
  • Save akey7/94ff0b4a4caf70b98f0135c1cd79aff3 to your computer and use it in GitHub Desktop.
Save akey7/94ff0b4a4caf70b98f0135c1cd79aff3 to your computer and use it in GitHub Desktop.
How to play a NumPy array with audio directly to a speaker.
# Use the sounddevice module
# http://python-sounddevice.readthedocs.io/en/0.3.10/
import numpy as np
import sounddevice as sd
import time
# Samples per second
sps = 44100
# Frequency / pitch
freq_hz = 440.0
# Duration
duration_s = 5.0
# Attenuation so the sound is reasonable
atten = 0.3
# NumpPy magic to calculate the waveform
each_sample_number = np.arange(duration_s * sps)
waveform = np.sin(2 * np.pi * each_sample_number * freq_hz / sps)
waveform_quiet = waveform * atten
# Play the waveform out the speakers
sd.play(waveform_quiet, sps)
time.sleep(duration_s)
sd.stop()
@LithiumXoul
Copy link

Is something similar possible by converting pydub audio segment to numpy array and then playing that?

@hemantmayatra
Copy link

below code works fine for me. Here wdata is ndarray and sr is sampling rate. for read scipy is used and playing pyaudio is used.

import pyaudio
from scipy.io import wavfile

sr, wdata=wavfile.read('house_lo.wav')

p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(1), channels = 1, rate = sr, output = True)
stream.write(wdata)
stream.stop_stream()
stream.close()
p.terminate()

@jenca-adam
Copy link

Is something similar possible by converting pydub audio segment to numpy array and then playing that?

Just use
arr = my_audio_segment.get_array_of_samples() sd.play(arr, my_samplerate)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment