banner



Alexa Loop Mode Not Working 2020

How to play YouTube sound from your Alexa

Introduction

Have you e'er wanted to ask Alexa to play the sound of a YouTube video? Just say "Alexa, Inquire Hey Tube to play Whitesnake" and mind to a bang-up Whitesnake track from YouTube.

In this article, I volition show how to build a Custom Alexa Skill to connect your Amazon Echo device to YouTube.

Note: Proceed in mind this skill will non be published in Amazon Store product, and tin merely be used in evolution mode. This is non an Amazon approved Skill and should only be used for educational purposes.

Alexa Custom Skill

The Alexa custom skill is a combination of two main components:

https://github.com/bignerdranch/developing-alexa-skills-solutions/blob/main/coursebook/coursebook.pdf

The skill interface defines how your skill volition behave:

  • A ready of "intents" that correspond deportment that users tin do with your skill.
  • A prepare of "sample utterances" that specify the words and phrases users tin can say to invoke those intents. You map these utterances to your intents — this mapping forms the "interaction model" for the skill.
  • An "invocation proper name" that identifies the skill. The user includes this name when initiating a conversation with your skill.

The skill service contains your code logic to handle the intents and perform actions. The service is deployed as a backend resource. For this exercise — JavaScript deployed in AWS Lambda

Skill Flow

This is the custom skill flow to exist adult:

  • The flow starts with a welcome bulletin and expects a video query name.
  • When asked to play a certain video, Alexa Interface calls the service using the query as the parameter.
  • The service calls YouTube API to search for a video, then returns the URL to Alexa.
  • Alexa starts playing the audio from the video URL.
  • At any time the user can ask Alexa to finish playing. Alexa will stop the sound track and say "Goodbye".

Let'due south Start

The easiest way to create a new Alexa Skill is past using ASK CLI.

Before starting, make sure y'all accept an Amazon Developers Account, Node installed, AWS Account, AWS CLI, and Ask CLI installed.

For a complete detailed guide setup of your surroundings check out my previous article Quickly Build an Alexa Skill Using ASK CLI.

Let's outset past creating the new skill construction: $ ask new:

ask new

Select:

  • NodeJS as the programming linguistic communication
  • AWS Lambda as the backend resource
  • Hello world as the starter template
  • Choose a skill name: alexa-skill-heytube
  • Choose a folder name: alexa-skill-heytube

Change to your new directory:$ cd alexa-skill-heytube/lambda

Install your packages: $ npm install

Skill Service

Open your favourite code editor. I'chiliad using Visual Studio Lawmaking.

This is your starting skill structure:

vs code skill structure

The skill service files are located in the skill-package binder.

The skill bundle contains all the resources used past the Enquire platform — skill manifest, interaction models, and assets.

Interaction Models

The interaction model resolves the spoken words into specific intent events. You define the words that should map to particular intent names in the interaction model by providing a list of sample utterances. A sample utterance is a cord that represents one possible fashion a user may talk to the skill. These utterances are used to generate a natural language understanding model. This resolves users voice to our skills intents.

The name of the interaction model is <locale>.json, for example en-GB.json.

Note: My Alexa is configured for en-GB, update your file name co-ordinate to your configuration, such as en-The states or others.

Open up iteractionModels/en-GB.json file:

Equally with any json file, pay shut attention to formatting:

  • Update invocationName to the name of your skill:
    "invocationName": "hey tube"
  • Delete HelloWorldIntent, AMAZON.NavigateHomeIntent
  • Create new intent to get a YouTube video:
            {
"name": "GetVideoIntent",
"slots": [{
"name": "videoQuery",
"blazon": "VIDEOS"
}],
"samples": [
"search for {videoQuery}",
"find {videoQuery}",
"play {videoQuery}",
"outset playing {videoQuery}",
"put on {videoQuery}"
]
},

Add standard required intents for audio skills: AMAZON.PauseIntent and AMAZON.ResumeIntent:

            {
"proper noun": "AMAZON.PauseIntent",
"slots": [],
"samples": []
},
{
"name": "AMAZON.ResumeIntent",
"slots": [],
"samples": []
}

We will also demand to define a blazon called VIDEOS.

Add the following in the types section:

            {
"proper noun": "GetVideoIntent",
"slots": [{
"name": "videoQuery",
"type": "VIDEOS"
}],
"samples": [
"search for {videoQuery}",
"observe {videoQuery}",
"play {videoQuery}",
"get-go playing {videoQuery}",
"put on {videoQuery}"
]
},

Annotation: If necessary rename or create a copy of your json file according to your Alexa configured language, similar en-Usa.json.

Skill manifest

The skill manifest is the JSON representation of your skill and provides Alexa with all the required metadata. The interaction model and business relationship linking schemas, if used, are separate.

Open up skill.json. Update your locale'southward information with your skill summary, example phrases, name, and clarification. You can likewise add small and big icons of your skill in png format:

            "locales": {
"en-GB": {
"summary": "Alexa Hey Tube Skill",
"examplePhrases": [
"Alexa open hey tube"
],
"keywords": [
"audio",
"streaming",
"youtube"
],
"name": "Hey Tube",
"description": "Alexa Skill to heed to youtube audio",
"smallIconUri": "https://alexademo.ninja/skills/logo-108.png",
"largeIconUri": "https://alexademo.ninja/skills/logo-512.png"
}
}

Update the category to STREAMING_SERVICE:

            "category": "STREAMING_SERVICE",          

Enable the audioplayer interface API. This volition enable the Alexa skill to play audio files:

            "apis": {
"custom": {
"interfaces": [{
"type": "AUDIO_PLAYER"
}]
}
}

The complete skill.json is bachelor here:

skill.json

YouTube Information API central

Your application must accept authority credentials to be able to use the YouTube information API.

Using the YouTube API does not incur whatsoever budgetary cost for the entity calling the API. If yous become over your quota a 403 Error volition be returned past the API. Gratis usage is limited to 100000 units per mean solar day — more than plenty for our usage.

Follow the steps below to get your YouTube API key:

  1. Head over to the Google developers console
  2. Create a new project by clicking the Select projection dropdown right next to the logo. Click the New Project button and requite it a name.
  3. Select your projection by choosing it in the Select Dropdown directly next to the logo in the header.
  4. Click the Enable APIs and Services push button.
  5. Search for youtube information.
  6. Click on the Youtube Data API v3.
  7. Click the blueish enable button.
  8. In the dashboard, click Credentials on the left sidebar.
  9. Click the Create Credential button.
  10. SelectAPI Key.
  11. Re-create your new generated key and relieve it for at present.

Securing the API key

Google provides the post-obit guidelines to secure your API key:

When you apply API keys in your applications, ensure that they are kept secure during both storage and transmission. Publicly exposing your credentials can consequence in your account being compromised, which could lead to unexpected charges on your account. To help go along your API keys secure, follow these best practices:

  • Do not embed API keys directly in code. API keys that are embedded in lawmaking tin can be accidentally exposed to the public. For example, you may forget to remove the keys from the code that you share. Instead of embedding your API keys in your applications, store them in environs variables or files outside your application'south source tree.
  • Practise non store API keys in files inside your application's source tree. If y'all store API keys in files, go along the files outside your application's source tree to ensure your keys practise not end upwards in your source lawmaking command system. This is particularly important if yous utilize a public source code management system such as GitHub.
  • Set up upward application and API key restrictions. Past adding restrictions, you can reduce the impact of a compromised API key.
  • Delete unneeded API keys to minimize exposure to attacks.
  • Periodically regenerate your API keys. You can regenerate API keys from the Credentials page by clicking the regenerate key for each key. Then, update your applications to utilize the newly-generated keys. Your old keys will continue to work for 24 hours after you generate replacement keys.
  • Review your code before publicly releasing information technology. Ensure that your code does not incorporate API keys or whatsoever other private information earlier yous make your lawmaking publicly available.

Skill Lawmaking

At present we're ready to develop our skill in NodeJS.

Open up lambda/index.js. The alphabetize.js volition starting time list your intent handlers created by Inquire CLI.

Intent handlers

An "intent" represents an activity that fulfills a user's spoken request. This will trigger intent handlers defined in your lambda handler alphabetize.js. Intent handlers receive an incoming asking and return an appropriate response.

  • Congenital-in intents are predefined for mutual deportment that you lot can implement in your custom skill without providing any sample utterances. The standard intents are used for mutual, general deportment such as stopping, canceling, and asking for assist. Here'southward a list of available standard built-in intents:

Let's edit the standard intent handlers:

  • LaunchRequestHandler: this method will handle the launch of our skill.

"Alexa, open up hey tube"

Edit your Welcome Bulletin and add a re-prompt to repeat the welcome:

LaunchRequestHandler
  • CancelAndStopIntentHandler: This method will pause the sound from being played. It treats, "Stop", "Cancel" and "Intermission" as keywords

"Alexa, terminate music"

CancelAndStopIntentHandler

Let'southward create a custom intent handler to handle the GetVideo telephone call.

GetVideoIntentHandler : this method will handle the search for a YouTube video and render the audio stream and so Alexa can play it.

I will use a controller helper function to brand the lawmaking cleaner.

"Alexa, play Whitesnake"

Helper functions

The controller helper has three methods:

  • search: Calls YouTube API to search a video based on query received past the user. The search returns video information such as the video ID and title.
  • play: Once the video information is received, it calls some other YouTube API to receive the stream and convert it to the 140 quality required by Alexa. The method will return a URL. It then calls addAudioPlayerPlayDirective to start playing the audio stream.
  • stop: Calls addAudioPlayerStopDirective to stop playing the audio stream.

Search videos

To search YouTube videos, I'm using the npm package yt-list.

Let'southward install it. In your lambda folder type: $ npm i --salvage yt-list.

Add the import at the top of the file:

const ytlist = require("yt-list");

Play audio

To play the audio stream I'm using another npm packet, ytdl-core. Permit's install it.

In your lambda binder blazon $ npm i --save ytdl-cadre.

Add the import at the top of the file: const search = require("ytdl-core");

Both methods are beneath:

Search and Get Audio from YouTube

Skill architect

The last part is to add the request handler to SkillBuilder. The skill builder is the entry betoken of your skill, routing all requests and responses:

Skill Builder

The complete source code is available in my GitHub:

Deploy Your Skill

Quickly deploy your skill with ASK CLI without going to the console. Become to your skill folder root and blazon: $ ask deploy.

ASK volition automatically:

  • Deploy skill metadata: Package and upload the contents of the skill's skill-package/ directory to Alexa Skills using the Skill Package API. If this is the first fourth dimension you've deployed the skill, the control creates a new skill in the configured Amazon programmer account.
  • Build a skill lawmaking under the lambda/ directory and package the build artifacts for deployment to AWS. This includes installing the skill's dependencies and producing any build artifacts. For a skill written for Node.js, this means running npm install to install dependencies declared in package.json and packaging it with the JavaScript source code.
  • Deploy skill infrastructure edifice artifacts to the configured AWS Lambda part. If this is the first time the skill has been deployed and a Lambda ARN has not been configured, the command creates a new Lambda part.
  • Enable skill

Afterward a while, your skill is deployed in AWS and prepare to be used in evolution mode (not publicly available, yet).

Validate your deployment:

  • Sign in to AWS Console → Lambda

Verify your new skill as a lambda role is created.

Sign in to the Alexa developer panel and verify your new skill has been created. You tin can click on information technology to see the details, but I don't recommend editing any fields through the console.

Congratulations — your start skill is properly deployed in Alexa and AWS Lambda. Everything is done through the CLI without going through the console.

Yous can edit your code in Visual Studio Code, save it and but type $ ask deploy to redeploy your skill. This will save y'all a lot of fourth dimension while developing.

If y'all are using the skill.json file available in my repo you might get the error below:

"message": "The trigger setting for the Lambda arn:aws:lambda:eu-westward-ane:924338216746:function:ask-heytube-default-default-1595666765538 is invalid."

This is considering inquire is using the endpoint uri created previoulsy for my instance. In the skill.sjon file delete the whole section including the comma before:

            ,
"endpoint": {
"uri": "arn:aws:lambda:eu-west-1:924338216746:function:inquire-heytube-default-default-1609336787911"
}

Now try again $ ask deploy

A new endpoint uri should be updated in the file

Last Configs

The final configuration is to add your environs variable to Lambda. Unfortunately, I couldn't detect a way to add environment variables with ASK CLI, so my way is going to from AWS Console to Lambda.

Click on the service name and roll to the "Environment variables "section. Add your variable, YOUTUBE_API_KEY, with the value being the central you created above in the Google Developers Console.

Add together your YOUTUBE_API_KEY

Also, increase your service timeout in "Bones settings" to 15 seconds.

Increase timeout

Now permit's update the local service revisionId.

If y'all endeavour to deploy your service now, considering you've updated configuration through the console, you'll get the post-obit error:

[Error]: The current revisionId (The revision ID for Lambda ARN (arn:aws:lambda:eu-west-1:924338216746:office:ask-heytube-default-default-1595666765538) should be a4d5f786–96c3–414c-9b94–4b8ecade411b, but found 1dcd52fb-8626–4f63-a4cc-c5fc59454f0b. Please solve this revision mismatch and re-deploy once again.

The easiest mode to resolve this is:

  1. Open up to your .ask/ask-states.json file
  2. Find the "revisionId": "XXXX"
  3. Delete the value in the "revisionId": ""
  4. Deploy the skill: $ ask deploy

Test the Showtime Skill

To test your skill from the command line, run enquire dialog and specify a locale supported by your skill:

            $ enquire dialog --locale en-GB          

The control opens an interactive terminal in which you tin can simulate a multi-turn chat with Alexa:

Open your skill and simulate a conversation:

                          User  > Alexa open up hey tube              
Alexa > Welcome to Hey Tube. inquire to play a video to offset listening.
User > play Whitesnake
Alexa > Playing Whitesnake - Here I Go Over again '87 (Official Music Video)
User > .quit

The first test is done. If yous have an Alexa device, you can exam this conversation in your Alexa — you lot should get the same results and hear a swell song from Whitesnake.

You can brand any changes to your skill and redeploy it.

You can automate the replay by using a preformatted .json file to salvage some time in your tests.

Use .record to create a repeatable JSON exam file:

            User  > .record          

I created happyPath.json as an example:

            $ ask dialog --locale en-GB --replay happyPath.json          

You can too test it through the Alexa Developers Panel:

Alexa Developers Console

Final Remarks

The complete source code for this skill is available on my GitHub:

For a consummate detailed guide setup of your environs, check out my previous article Speedily Build an Alexa Skill Using ASK CLI — Learn to create your first custom Hello World Alexa Skill.

Check out the multi-rail skill version enhancing the single-runway skill to a complete audio player to play, finish, resume, skip, loop, and play the next related audio track from YouTube.

Call back — some videos may not play as they're protected on YouTube.

Happy Coding!

Source: https://betterprogramming.pub/how-to-play-youtube-audio-from-your-alexa-e2d4fb8b5ce9

0 Response to "Alexa Loop Mode Not Working 2020"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel