Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...