Running a timer in background for x seconds [Alexa Skill]

Viewed 414

I am making a function that is returning audio but only for x seconds.

If the user says

play me a song for x seconds

I am playing the song but need it to cancel after X seconds. Therefore, my plan is before running the audio to start the timer for x seconds. Then once the timer is up to set a notification to another function that will return a new voice saying your time is up.

I've gotten the logic down although I need a way to start a background timer.

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

Currently:

-> On Launch

-> return start audio

-> I will need to pass in X Seconds

-> X Seconds will start timer

-> Once that timer finishes call another function that stops

If someone can lead me in the right direction like showing me how to run background timer with x seconds then to call another function then I will be able to take over and scale this even higher.

2 Answers

Because Alexa works as a request/response application, once you send the response, there's no more way to control the playback until the user does something and a new request comes to your handler.

I can imagine two possible ways you can achieve the desired functionality. Either generate a short audio clip on the fly (with something like FFmpeg) or have them pre-generated for all the possible durations (1s, 2s, 3s...) and serve the appropriate one.

You can do something like this:

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
Related