Search code examples
pythonaudio

Way to play a sound in python on Linux without providing a file?


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.


Solution

  • 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