使用下面的代码时会播放声音:
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
但是当我在一个函数中使用它时它停止工作:
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()
我试图将音频分配给一个变量并返回它有效:
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
但我想在不同的功能中使用声音:
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()
我如何进行这项工作以及导致这种行为的原因是什么?笔记本的内核是 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()
我不知道如何返回声音并在同一个函数中安排下一个事件。
原文由 Geart van der Ploeg 发布,翻译遵循 CC BY-SA 4.0 许可协议
我遇到了同样的问题,我打电话时播放了声音:
但是当它在函数内部时它不起作用。问题是函数调用并没有真正播放声音,它实际上是由返回到 Jupyter 输出的结果 HTML 播放的。
因此,为了克服这个问题,您可以使用 IPython 中的 display() 函数强制该函数呈现 HTML。这将起作用: