【问题标题】:Running a timer in background for x seconds [Alexa Skill]在后台运行计时器 x 秒 [Alexa Skill]
【发布时间】:2019-01-13 23:37:04
【问题描述】:

我正在制作一个返回音频但仅持续 x 秒的函数。

如果用户说

给我播放​​一首歌 x 秒

我正在播放歌曲,但需要在 X 秒后取消。因此,我的计划是在运行音频之前启动计时器 x 秒。然后,一旦计时器到了,就将通知设置到另一个函数,该函数将返回一个新的声音,说你的时间到了。

虽然我需要一种方法来启动后台计时器,但我已经搞定了逻辑。

def start_audio():
    card_title = "Start Audio"
    session_attributes = {}


    sound_url = 'https://s3.amazonaws.com/........mp3'

    speech_output = "<speak><audio src='{}'/> </speak>".format(sound_url)



    should_end_session = False
    return build_response(session_attributes, myCustomSSML(
        card_title, speech_output, None, should_end_session))

def myLaunchIntent():
    """ If we wanted to initialize the session to have some attributes we could
    add those here
    """
    session_attributes = {}
    card_title = "Welcome"
    speech_output = "Welcome to your custom Alexa application!"

    return start_audio()

目前:

-> 启动时

-> 返回开始音频

-> 我需要通过 X 秒

-> X 秒将启动计时器

-> 一旦计时器完成调用另一个停止的函数

如果有人可以引导我朝着正确的方向前进,例如向我展示如何在 x 秒内运行后台计时器然后调用另一个函数,那么我将能够接管并将其扩展得更高。

【问题讨论】:

  • 必须是定时器吗?您可以将歌曲开始的时间存储在变量中,例如 startTime。然后反复检查 currentTime - startTime === 用户所需的长度。也许在一个while循环中,虽然我不确定这是多么优化。

标签: python python-3.x alexa alexa-skills-kit


【解决方案1】:

因为 Alexa 作为请求/响应应用程序工作,一旦您发送响应,就无法控制播放,直到用户执行某项操作并且新请求到达您的处理程序。

我可以想象两种可能的方式来实现所需的功能。要么即时生成一个简短的音频剪辑(使用 FFmpeg 之类的东西),要么为所有可能的持续时间(1 秒、2 秒、3 秒...)预先生成它们并提供适当的音频。

【讨论】:

  • 在阅读本文之前,我确实尝试了我的功能,是的,您是正确的。它只在请求/响应时运行。我会尝试做预先定义的音频长度。
【解决方案2】:

你可以这样做:

def start_audio():
  card_title = "Start Audio"
  session_attributes = {}


  sound_url = 'https://s3.amazonaws.com/........mp3'

  speech_output = "<speak><audio src='{}'/> </speak>".format(sound_url)



  should_end_session = False
  return build_response(session_attributes, myCustomSSML(card_title, speech_output, None, should_end_session))

def myLaunchIntent():
  """ If we wanted to initialize the session to have some attributes we could
  add those here
  """
  session_attributes = {}
  card_title = "Welcome"
  speech_output = "Welcome to your custom Alexa application!"

from threading import Event as event
play="Y"
number=0
x=int(input("Audio length:"))
return start_audio()
for i in range(x):
  if play="Y":
    event().wait(1)
    number+=1
    if number==play:
      play="N"
  else:
    #insert way to stop audio here

【讨论】:

  • event().wait(1) 函数最终可能会暂停整个音频,因此我建议找到另一个等待(不暂停整个程序)一秒钟的函数,但结构应该保持不变一样的。
猜你喜欢
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
相关资源
最近更新 更多