可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
You could use an external module with python. Try adding this s.play()
call from Snack Sound Toolkit at the end of the cell.
The Snack Sound Toolkit can play wav, au and mp3 files.
s = Sound()
s.read('sound.wav')
s.play()
this question is basically a duplicate of:
Play a Sound with Python.
The above code-snipit was from @csexton in that question.
回答2:
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
回答3:
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.
回答4:
Here is another version (Python-side mostly) which works well with JupyterLab:
from time import time
from IPython import get_ipython
from IPython.display import Audio, display
class Beeper:
def __init__(self, threshold, **audio_kwargs):
self.threshold = threshold
self.start_time = None # time in sec, or None
self.audio = audio_kwargs
def pre_execute(self):
if not self.start_time:
self.start_time = time()
def post_execute(self):
end_time = time()
if self.start_time and end_time - self.start_time > self.threshold:
audio = Audio(**self.audio, autoplay=True)
display(audio)
self.start_time = None
beeper = Beeper(5, url='http://www.soundjay.com/button/beep-07.wav')
ipython = get_ipython()
ipython.events.register('pre_execute', beeper.pre_execute)
ipython.events.register('post_execute', beeper.post_execute)
The beep will automatically be emitted after each code execution which took more than 5 seconds, but the consecutive executions are not counted together.
For example:
# cell 0:
from time import sleep
# cell 1:
sleep(6) # will ring
If you then add another cell
# cell 3:
sleep(3) # it won't ring
Tested with JupyterLab 0.32.1 and Jupyter notebook 5.5.0.
Edit: to reduce the clutter of the shown audio players I use following snippet (for Python older than 3.6 you need to use .format()
instead of f-strings):
from IPython.display import Audio, display
class InvisibleAudio(Audio):
def _repr_html_(self):
audio = super()._repr_html_()
audio = audio.replace('<audio', f'<audio onended="this.parentNode.removeChild(this)"')
return f'<div style="display:none">{audio}</div>'
and then use InvisibleAudio
instead of Audio
in post_execute
.
回答5:
What about typing the code once and having it work after execution of every cell if it executes longer than given amount of time?
Just create and execute a cell with following JavaScript (adjusting timeout and sound)
%%javascript
(function(){
var startTime;
$([Jupyter.events]).on('execute.CodeCell', function(event, target)
{
startTime = performance.now();
});
$([Jupyter.events]).on('finished_iopub.Kernel', function(event, target)
{
var endTime = performance.now();
if(endTime - startTime > 5 * 1000)
{
var audio = new Audio('http://www.soundjay.com/button/beep-07.wav');
audio.play();
}
});
})()
After that, you should hear the 'beep' after each code execution which took more than 5 seconds. For example:
# cell 0:
from time import sleep
# cell 1:
sleep(6) # will ring
If you then add another cell
# cell 3:
sleep(3) # it won't ring
Unless you execute several cells at a time:
# cell 4:
sleep(3)
# cell 5:
sleep(3) # will ring if queued for execution after cell 4
Tested with Jupyter notebook 5.5.0.
The code might require further improvements (feel free to edit). To make it work on Google Colab, one needs to load jQuery on their own.
Does not seem to work with JupyterLab yet.
To turn off, use:
%%javascript
// a slightly better version would unbind only the handlers defined above
$([Jupyter.events]).unbind('execute.CodeCell')
$([Jupyter.events]).unbind('finished_iopub.Kernel')
You can also use base64 encoded beep sound (see this answer and this gist):
var audio = new Audio('data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZju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5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=');
回答6:
Based on @krassowski's answer, here's my solution to this. The main difference is that @krassowski's runs after every every "long" cell execution (where you define what "long" means); I prefer to explicitly say when I want the sound played, so I've wrapped this into a magic (gist here and copied below).
"""
Adds a magic to IPython which will play a given sound when a cell finishes running.
Requires Python 3.6+.
Put this file in, e.g., ~/.ipython/profile_default/startup to load this magic on startup.
USAGE:
```
%%notify
run_long_function()
```
If you want, you can specify the URL of the audio file to play:
```
%%notify -u "{URL}"
run_long_function()
```
To always play your preferred audio file, just change the default below.
"""
from IPython.display import HTML, Audio, display
from IPython.core.magic_arguments import magic_arguments, argument, parse_argstring
from IPython.core.magic import cell_magic, Magics, magics_class
from IPython import get_ipython
class _InvisibleAudio(Audio):
"""
An invisible (`display: none`) `Audio` element which removes itself when finished playing.
Taken from https://stackoverflow.com/a/50648266.
"""
def _repr_html_(self) -> str:
audio = super()._repr_html_()
audio = audio.replace(
"<audio", '<audio onended="this.parentNode.removeChild(this)"'
)
return f'<div style="display:none">{audio}</div>'
@magics_class
class NotificationMagics(Magics):
"""
Inspired by https://stackoverflow.com/a/50648266.
"""
@cell_magic
@magic_arguments()
@argument(
"-u",
"--url",
help="URL of sound to play",
default="https://freewavesamples.com/files/E-Mu-Proteus-FX-CosmoBel-C3.wav",
)
def notify(self, line: str, cell: str):
args = parse_argstring(self.notify, line)
ret = self.shell.ex(cell)
audio = _InvisibleAudio(url=args.url, autoplay=True)
display(audio)
return ret
get_ipython().register_magics(NotificationMagics)