Vladimir Vargas
Vladimir Vargas

Reputation: 1824

Playing sound in a loop with python in jupyter notebook

I am trying to use ipython to display an audio. My idea is that I have a loop performing some tasks, and when the tasks for that loop are completed I want an alarm to sound. Therefore, the loop would essentialy look like this:

for i in range(5):
    if True:
        IPython.display.Audio("alarm.mp3", autoplay=True)
    else:
        pass

However, this does not play any sound at all, nor creates the widget. What other libraries can I use, or how can I fix this using the ipython?

Upvotes: 2

Views: 2753

Answers (2)

Rafay Khan
Rafay Khan

Reputation: 1240

if you are still looking into this. I just found out about playsound. Very simple bare bones API, it's cross-platform and doesn't even have any dependencies.

You can call it simply in Jupyter notebook, either in a blocking manner(i.e. on the main thread) or asynchronously.

import playsound
playsound.playsound(path, block=True)

check it out here

Upvotes: 1

Vladimir Vargas
Vladimir Vargas

Reputation: 1824

The library sounddevice does the trick. Convert audio file to wav and then:

from scipy.io import wavfile
import sounddevice as sd

fs, data = wavfile.read('alarm.wav')
for i in range(5):
    if True:
        sd.play(data, fs)
    else:
        pass

This does the trick perfectly.

Upvotes: 2

Related Questions