Gea*_*oeg 4 python audio scheduled-tasks ipython jupyter-notebook
使用下面的代码时,声音播放:
import IPython.display as ipd
import numpy
sr = 22050 # sample rate
T = 0.5 # seconds
t = numpy.linspace(0, T, int(T*sr), endpoint=False) # time variable
x = 0.5*numpy.sin(2*numpy.pi*440*t) # pure sine wave at 440 Hz
ipd.Audio(x, rate=sr, autoplay=True) # load a NumPy array
Run Code Online (Sandbox Code Playgroud)
但是当我在函数中使用它时,它停止工作:
import IPython.display as ipd
import numpy
def SoundNotification():
sr = 22050 # sample rate
T = 0.5 # seconds
t = numpy.linspace(0, T, int(T*sr), endpoint=False) # time variable
x = 0.5*numpy.sin(2*numpy.pi*440*t) # pure sine wave at 440 Hz
ipd.Audio(x, rate=sr, autoplay=True) # load a NumPy array
SoundNotification()
Run Code Online (Sandbox Code Playgroud)
我试图将音频分配给一个变量并返回它的工作原理:
import IPython.display as ipd
import numpy
def SoundNotification():
sr = 22050 # sample rate
T = 0.5 # seconds
t = numpy.linspace(0, T, int(T*sr), endpoint=False) # time variable
x = 0.5*numpy.sin(2*numpy.pi*440*t) # pure sine wave at 440 Hz
sound = ipd.Audio(x, rate=sr, autoplay=True) # load a NumPy array
return sound
sound = SoundNotification()
sound
Run Code Online (Sandbox Code Playgroud)
但我想在不同的函数中使用声音:
import IPython.display as ipd
import numpy
def SoundNotification():
sr = 22050 # sample rate
T = 0.5 # seconds
t = numpy.linspace(0, T, int(T*sr), endpoint=False) # time variable
x = 0.5*numpy.sin(2*numpy.pi*440*t) # pure sine wave at 440 Hz
sound = ipd.Audio(x, rate=sr, autoplay=True) # load a NumPy array
return sound
def WhereIWantToUseTheSound():
sound = SoundNotification()
sound
WhereIWantToUseTheSound()
Run Code Online (Sandbox Code Playgroud)
我如何进行这项工作以及是什么导致了这种行为?笔记本的内核是 Python 3。
编辑:我想在预定事件中播放声音:
import IPython.display as ipd
import numpy
import sched, time
sound = []
def SoundNotification():
sr = 22050 # sample rate
T = 0.5 # seconds
t = numpy.linspace(0, T, int(T*sr), endpoint=False) # time variable
x = 0.5*numpy.sin(2*numpy.pi*440*t) # pure sine wave at 440 Hz
sound = ipd.Audio(x, rate=sr, autoplay=True) # load a NumPy array
return sound
def do_something(sc):
print("Doing stuff...")
# do your stuff
sound_ = SoundNotification()
s.enter(interval, 1, do_something, (sc,))
return sound_
s = sched.scheduler(time.time, time.sleep)
interval = int(input("Interval between captures in seconds: "))
s.enter(0, 1, do_something, (s,))
s.run()
Run Code Online (Sandbox Code Playgroud)
我不知道如何在同一函数中返回声音并安排下一个事件。
我遇到了同样的问题,当我打电话时播放声音:
from IPython.display import Audio
Audio('/path/beep.mp3', autoplay=True)
Run Code Online (Sandbox Code Playgroud)
但是当它在函数内部时它不起作用。问题是函数调用并没有真正播放声音,它实际上是由返回到 Jupyter 输出的结果 HTML 播放的。
因此,为了克服这个问题,您可以使用 IPython 中的 display() 函数强制该函数呈现 HTML。这将起作用:
from IPython.display import Audio
from IPython.core.display import display
def beep():
display(Audio('/path/beep.mp3', autoplay=True))
beep();
Run Code Online (Sandbox Code Playgroud)