I need a piece of code that plays a sound, any sound to indicate an operation is finished. It should work on Linux and play some kind of sound on the currently selected audio output. I don't want to have to provide a file, I just need some code that can play sound that is easy to copy paste in a jupyter notebook and works on Linux.
2 Answers
Just for fun another way
import numpy as np import sounddevice as sd def bip(freq, dur, a=0, d=0, s=1, r=0): t=np.arange(0,dur,1/44100) env=np.interp(t, [0, a, (a+d), dur-r, dur], [0, 1, s, s, 0]) sound=np.sin(2*np.pi*freq*t)*env sd.play(sound, samplerate=44100) # Example # A banal computer bip bip(880, 0.1) # With a more sophisticated envelope. Djdoing bip(880,0.4, a=0, d=0.24, s=0.28, r=0.09) # Softer attack bip(440,0.6, a=0.1, d=0.2, s=0.5, r=0.2) It is more or less the way good old 8 bits computers were playing sound: with the specification of a frequency and an envelope. And people, at that time, myself included, but I forgot everything, knew what kind of envelope to use to imitate a piano, a trumpet, etc. Well, we weren't very picky on the quality. And of course, at that time, it was not the CPU computing the enveloped sinus; that was just some hardware oscillator.
We could make this fancier by dealing with harmonics (having an array of adsr, for example, one for each harmonic). But I think the objective was to keep it simple, not to rebuild a 90s synthetizer. Besides, there are certainly some synthetizer/midi libraries out there.
2 Comments
pyaudio or IPython.display.audio. I am used to sounddevice because, with my students (who are learning linear algebra, not sound handling. Sound is just the fun application) I wanted the audio part to be just a one-liner, and sounddevice has this, synchronous, blocking, API (and also a non-blocking on) that makes it very simple. But well, my point in this comment was more about how to synthetize quickly a sound, rather than how to send it to the sound card afterward.import numpy as np import sounddevice as sd from time import sleep # Parameters for the sine wave duration = 5 # Duration in seconds frequency = 440 # Frequency in Hz (A4 note) # Generate the time axis sample_rate = 44100 # Sample rate in Hz t = np.linspace(0, duration, int(duration * sample_rate), endpoint=False) # Generate the sine wave waveform = np.sin(2 * np.pi * frequency * t) # Play the sine wave sd.play(waveform, sample_rate) sleep(0.5) sd.stop() waveform = np.sin(4 * np.pi * frequency * t) sd.play(waveform, sample_rate) sleep(0.5) sd.stop() waveform = np.sin(5 * np.pi * frequency * t) sd.play(waveform, sample_rate) sleep(0.5) sd.stop() sd.wait() this one works fine
print("\a")