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()
@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