gpt4 book ai didi

python - 在函数中使用IPython.display.audio在jupyter笔记本中播放音频无法正常工作

转载 作者:行者123 更新时间:2023-12-02 22:48:20 28 4
gpt4 key购买 nike

使用下面的代码时,声音会播放:

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()

我不知道如何在同一函数中返回声音并安排下一个事件。

最佳答案

我遇到了同样的问题,我打电话时播放了声音:

from IPython.display import Audio 
Audio('/path/beep.mp3', autoplay=True)
但是当它在函数内部时,它不起作用。问题在于该函数调用并没有真正播放声音,它实际上是由返回到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();

关于python - 在函数中使用IPython.display.audio在jupyter笔记本中播放音频无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61573928/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com