Created
March 31, 2018 06:13
-
-
Save akey7/94ff0b4a4caf70b98f0135c1cd79aff3 to your computer and use it in GitHub Desktop.
How to play a NumPy array with audio directly to a speaker.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just use
arr = my_audio_segment.get_array_of_samples() sd.play(arr, my_samplerate)