Automatically play sound in IPython notebook

I often run long-running cells in my IPython notebook. I'd like the notebook to automatically beep or play a sound when the cell is finished executing. Is there some way to do this in iPython notebook, or maybe some command I can put at the end of a cell that will automatically play a sound?

I'm using Chrome if that makes any difference.


TL;DR

At the top of your notebook

from IPython.display import Audio
sound_file = './sound/beep.wav'

sound_file should point to a file on your computer, or accessible from the internet.

Then later, at the end of the long-running cell

<code that takes a long time>

Audio(sound_file, autoplay=True)

This method uses the Audio tag built into Newer versions of iPython/Jupyter.

Note For Older Versions

Older versions without the Audio tag can use the following method.

Put this in a cell and run it before you want to play your sound:

from IPython.display import HTML
from base64 import b64encode

path_to_audio = "/path/to/snd/my-sound.mp3"
audio_type = "mp3"

sound = open(path_to_audio, "rb").read()
sound_encoded = b64encode(sound)
sound_tag = """
    <audio id="beep" controls src="data:audio/{1};base64,{0}">
    </audio>""".format(sound_encoded, audio_type)

play_beep = """
<script type="text/javascript">
    var audio = document.getElementById("beep");
    audio.play();
</script>
"""

HTML(sound_tag)

At the end of the cell you want to make a noise on completion put this:

HTML(play_beep)

How it works:

It reads a file from the filesystem using iPython's built in open and read methods. Then it encodes this into base64. It then creates an audio tag with the ID beep and injects the base64 data into it. The final piece of setup creates a small script tag that plays the sound.

This method should work in any browser that supports the HTML5 audio tag.

Note: if you'd rather not display the audio controls in your notebook, just remove the controls attribute from the variable named sound_tag


My favorite solution (no need for an external module) :

import os
os.system("printf '\a'") # or '\7'

Works on OS X.

However DaveP's remark still apply : it is not the browser playing the sound but the server.