annasxu
annasxu

Reputation: 11

Alexa Audio Player Directive

I'm trying to build an Alexa skill that can play an audio file. I'm trying to send an Audio Player Play directive in the Launch Request, but when I use this code, I get no response back from my Alexa. Does it look correct?

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
  },
  handle(handlerInput) {
    console.log('IN LAUNCHREQUEST');
    return handlerInput.responseBuilder
        .addDirective({
            type: 'AudioPlayer.Play',
            playBehavior: 'REPLACE_ALL',
            audioItem: {
                stream: {
                    token: "0",
                    url: "myurlhere",
                    offsetInMilliseconds: 0
                }
            }
        })
    }
};

Upvotes: 1

Views: 1722

Answers (2)

chejaras
chejaras

Reputation: 862

If you are using alexa sdk v2 (https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs) then you can use inbuilt methods to play audio. Following methods are available to play long form audio.

addAudioPlayerPlayDirective(playBehavior: interfaces.audioplayer.PlayBehavior, url: string, token: string, offsetInMilliseconds: number, expectedPreviousToken?: string, audioItemMetadata? : AudioItemMetadata): this;
addAudioPlayerStopDirective(): this;
addAudioPlayerClearQueueDirective(clearBehavior: interfaces.audioplayer.ClearBehavior): this;

More information can be found on https://ask-sdk-for-nodejs.readthedocs.io/en/latest/Building-Response.html

Following is a code snippet that I use in my lambda to play audio.

//Create Image to be displayed with song

const metadata = {
    title: 'Stopwatch Audio',
    art: {
        sources: [{
            url: imageUrl
        }]
    }
};
handlerInput.responseBuilder.speak(speechText).addAudioPlayerPlayDirective("REPLACE_ALL", audiofile, audiofile, 0, null, metadata).withShouldEndSession(true).getResponse();

Upvotes: 1

mcont
mcont

Reputation: 1933

You must return a "built" response, in the handler. So in you case the code would be:

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
  },
  handle(handlerInput) {
    console.log('IN LAUNCHREQUEST');
    return handlerInput.responseBuilder
        .addDirective({
            type: 'AudioPlayer.Play',
            playBehavior: 'REPLACE_ALL',
            audioItem: {
                stream: {
                    token: "0",
                    url: "myurlhere",
                    offsetInMilliseconds: 0
                }
            }
        })
        .getResponse();
        // ^^^ add this line
    }
};

Upvotes: 2

Related Questions