Search code examples
phpalexa-skills-kitalexa-voice-service

How to add multiple track to stream in alexa?


I am working on alexa for the first time and I am developing a music app. I need to add multiple track of one artist and play it continuously. I am unable to do so. However, one song is working properly but unable to add and play multiple song.

Here is my code,

$response = '{
        "version" : "1.0",

        "response" : {
            "outputSpeech": {
              "type": "PlainText",
              "text": "Playing song for Acon"
            },
            '.$card.',
            "directives": [
              {
                "type": "AudioPlayer.Play",
                "playBehavior": "REPLACE_ALL",
                "audioItem": {
                  "stream": {
                "token": "track1",
                "url": "https://p.scdn.co/mp3-preview/9153bcc4d7bef50eb80a809fa34e694f2854e539?cid=null",
                "offsetInMilliseconds": 0
                  }
                }
              }
            ],
            "shouldEndSession" : true
        }
    }';

Solution

  • Follow the above doc: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/custom-audioplayer-interface-reference#playbacknearlyfinished-request

    and then do this to enqueue the second song

    In PHP, the way you are handling other requests, you can handle AudioRequest too. For example.

    $data       = file_get_contents("php://input");
    $jsonData   = json_decode($data);
    
    if($jsonData->request->type === "AudioPlayer.PlaybackNearlyFinished")
    { 
        $response = '{
            "version" : "1.0",
            "response" : {
                "directives": [
                  {
                    "type": "AudioPlayer.Play",
                    "playBehavior": "ENQUEUE",
                    "audioItem": {
                      "stream": {
                    "token": "track2",
                    "expectedPreviousToken": "track1",
                    "url": "Your URL",
                    "offsetInMilliseconds": 3
                      }
                    }
                  }
                ],
                "shouldEndSession" : true
            }
        }';
        echo $response;
    } 
    

    This is the way you can handle all the AudioRequest.