【发布时间】:2020-05-03 11:48:44
【问题描述】:
当使用下面的代码播放声音时:
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()
我不知道如何在同一个函数中返回声音并安排下一个事件。
【问题讨论】:
标签: python audio jupyter-notebook ipython scheduled-tasks