How to add multiple track to stream in alexa? - php

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
}
}';

You need to wait for the AudioPlayer.PlaybackNearlyFinished request from Alexa. At that point, you can enqueue the next track to be played. It will come near the conclusion of the playback of the currently playing track.
Information on it is here:
https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/custom-audioplayer-interface-reference#playbacknearlyfinished-request
When replying with a directive to PlaybackNearlyFinished, be sure that:
You set the playBehavior to ENQUEUE
This will cause the next track to start after the current one finishes
You do NOT include the outputSpeech field
outputSpeech is not allowed when out of session. The session ends when the first stream begins playback.
This blog post that I wrote goes into more detail on approaches to developing and testing for the AudioPlayer interface:
https://bespoken.tools/blog/2016/10/10/unit-testing-alexa-skills

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.

Related

Unexpected number showing up at the end of JSON body

I am trying to write a simple demo that reads a json file with php and ajax. In js I have
// initial entry point
function main(){
var button = document.getElementById("button");
button.addEventListener("click",test);
button.addEventListener("click",getSummary);
}
function test(){
console.log("button was clicked");
}
function getSummary(){
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", processResponse, false);
console.log("sending request");
asyncRequest.open("GET","http://localhost/summary.php",true);
asyncRequest.send(null);
}
function processResponse(){
console.log("processing request");
if(asyncRequest.readyState==4 && asyncRequest.status==200){
console.log(asyncRequest.response);
}
}
summary.php
<?php
$data = readfile("summary.json");
header('Content-Type: text/json;charset=utf-8');
echo json_encode($data);
summary.json
{
"products":[
{
"product":"professional pencil",
"image":"pencil.jpg",
"description":"The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
},
{
"product":"coffee mug",
"image":"coffee_mug.jpg",
"description":"Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
},
{
"product":"programming book",
"image":"programming_book.jpg",
"description":"Learn how to program effectively by reading this book."
}
]
}
When I make a request I get an unusual 706 at the end of the response.
curl localhost/summary.php | Select Content -Expand Content | jq produces
{
"products": [
{
"product": "professional pencil",
"image": "pencil.jpg",
"description": "The most verstile tool any programmer can have. With this professional pencil you'll be able to sketch out plans and fix mistakes!"
},
{
"product": "coffee mug",
"image": "coffee_mug.jpg",
"description": "Keep your programming skills sharp and your coffee hot with this one of a kind coffee mug."
},
{
"product": "programming book",
"image": "programming_book.jpg",
"description": "Learn how to program effectively by reading this book."
}
]
}
706
Any help with this would be greatly appreciated.
For your summary.php you actually want it to be more like the following to do what you are intending to do
<?php
$data = file_get_contents("summary.json");
header('Content-Type: text/json;charset=utf-8');
echo $data;
json_encode isn't necessary when the data is already JSON text.
And, more importantly, readFile returns a number indicating the number of bytes read. That's the number in $data which you're then outputting and seeing in your results. readFile sends the actual file data direct to the output, not into a variable.
So your code can be shortened to simply
header('Content-Type: text/json;charset=utf-8');
readfile("summary.json");
Documentation: https://www.php.net/manual/en/function.readfile.php

Unable to set action for mobile and web platform

We are using Airship API to send push notification on mobile and web platforms and for deep linking we are using action like
"notification": {
"actions": {
"open": {
"type": "deep_link",
"content": "https://www.urbanairship.com/settings",
}
}
}
and web action is:
"notification": {
"actions": {
"open": {
"type": "url",
"content": "http://www.urbanairship.com"
}
},
}
Above parameters working well as individually but we want to use both parameters together like in attached screen shot "screenshot.png". We didn't find any solution on documentation that show how to use deep linking and web action together same as attached screen shot. So could you suggest us how to merge these parameters so that we can use deep linking action for mobile devices and web action for websites together?
I have solved this and may be useful for someone.
Here's an example payload:
{
"audience": "all",
"device_types": ["ios", "android", "web"],
"notification": {
"alert": "Opening this message will open a defined deep link.",
"actions": {
"open": {
"type": "deep_link",
"content": "prefs", // for mobile platform
"fallback_url": "https://airship.com" // for web platform
}
}
}
}

using php, how to fetch a specific data from dialogflow fulfillment JSON request and store the data into a php variable

Using php, how can I fetch specific data from dialogflow fulfillment JSON request and store the data into a php variable?
Here is the JSON response I 'm getting from my dialogflow agent
{
"responseId": "e9106589-2a41-47c4-bdde-8f3cee8f40da",
"queryResult": {
"queryText": "switch on cfl",
"action": "input.switchoncfl",
"parameters": {
"makeRequest": "cfl_on"
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"platform": "ACTIONS_ON_GOOGLE",
"simpleResponses": {
"simpleResponses": [
{
"textToSpeech": "Sure. Turning CFL on... Anything else can I help you with?",
"displayText": "Sure. Turning CFL on..."
}
]
}
}
],
"intent": {
"name": "projects/smarthome-cf277/agent/intents/5be27f38-105d-4854-b62d-ec3a6de80cc7",
"displayName": "1.1-Switch_on_CFL"
},
"intentDetectionConfidence": 1,
"languageCode": "en"
},
"originalDetectIntentRequest": {
"payload": {}
},
"session": "projects/smarthome-cf277/agent/sessions/ca0261aa-913f-96f1-b5aa-7755637d5ab7"
}
And here is my php code
<?php
header("Content-Type: application/json");
ob_start();
$content = json_decode(file_get_contents('php://input'),true);
$action = $content['parameters']['makeRequest'];
ob_end_clean();
?>
I want to store cfl_on value to $action variable. How can I do that? this php code does not work.
You just missed out the "queryResult" layer of the object.
$action = $content['queryResult']['parameters']['makeRequest'];

EmberJS API questions using PHP

I'm using Laravel/PHP to output some JSON for Ember to pick up.... a couple of things here.
First, my PHP looks like this (is there another way to send the data)
return Response::json([
'articles' => $articles->toArray()
], $statusCode);
This is what I am used to doing.
foreach($articles as $article) {
$response['articles'][] = [
'id' => $article->id,
'body' => $article->body,
'title' => $article->title
];
}
return Response::json([
'articles' => $articles->toArray()
], $statusCode);
The first PHP snippet works fine, but the second does not. I get all kinds of errors about resource types by Ember.
Next question is for Ember heads. Right now I am getting everything working with RESTAdapter but should I be using JSONAPIAdapter instead? When I try to get it working with JSONAPIAdapter and JSONAPISerializer I get this error
One or more of the following keys must be present: \"data\",
\"errors\", \"meta
. I can get that error to go away but then I get an error about an undefined type or an unknown resource.
Its not mandatory to use JSONAPIAdapter, but if you have control over the API then you can very well using it. API response should follow the format (http://jsonapi.org/format/)
Sample format for single resource object,
{
"data": {
"type": "articles",
"id": "1",
"attributes": {
// ... this article's attributes
}
}
}
Sample format for multiple resource objects,
{
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON API paints my bikeshed!"
}
}, {
"type": "articles",
"id": "2",
"attributes": {
"title": "Rails is Omakase"
}
}]
}

Facebook API GET recent post ID

I'm currently working on a little PHP 'script' that will automatically grab the Post ID from the most recent post on a Facebook page.
I have so far got this:
$status = $facebook->api("/645017715510822/feed?fields=id&limit=1&access_token=".$token, 'GET');
When I run this through my browser as https://graph.facebook.com/645017715510822/feed?fields=id&limit=1&access_token=XXXXXX then it will display the information that I need:
{
"data": [
{
"id": "645017715510822_1484080338478440",
"created_time": "2014-04-07T12:15:32+0000"
}
],
"paging": {
"previous": "https://graph.facebook.com/645017715510822/feed?fields=id&limit=1&access_token=XXXXXX&since=1396872932&__previous=1",
"next": "https://graph.facebook.com/645017715510822/feed?fields=id&limit=1&access_token=XXXXXX&until=1396872931"
}
}
What I am needing is for it to then grab only the 'id' and possibly print it?
My knowledge of PHP isn't wonderful and I've already tried searching related posts on here, but can't seem to find anything for my exact request, any assistance would be greatly appreciated.
Thanks.
Try this-
if( !empty($status['data']) )
{
foreach($status["data"] as $s)
{
$id = $s["id"];
}
}
else
{
//error
}

Categories