DEV Community

Cover image for Adding Voice Assistant to React Apps with Alan AI
Kanak
Kanak

Posted on

Adding Voice Assistant to React Apps with Alan AI

Have you used Cortana? Is Siri your best friend? Is it your go-to assistant whenever you face an obstacle?đź’­

If yes, then you would know how the development of voice assistants in our lives has made it easier since it requires minimal effort. Forecasts suggest that by 2024, the number of digital voice assistants will reach 8.4 billion units, a number higher than the world’s population, and 31% of smartphone users worldwide use voice search at least once a week.

A voice assistant is a digital assistant that uses voice recognition, language processing algorithms, and voice synthesis to listen to specific voice commands and return relevant information or perform specific functions as requested by the user.

Voice assistants are integrated into many of the devices we use daily, such as cell phones, computers, and smart speakers.

Would you like to have a voice assistant in your apps too? đź’¬

You might be thinking that to add an Intelligent Voice Interface to your app, you'll need to delve deep into machine learning and natural language processing, which will take a long time.

Here, Alan AI comes to your rescue. Alan AI is a B2B Voice AI platform for developers to deploy and manage voice interfaces for enterprise apps. It provides an AI-based backend as a service tool to add conversational AI to your apps.

It also recognizes user context and learns about the UI of your app to develop workflows and gets trained on your app's vocabulary.

With its developer-friendly console and documentation, it is easier for anyone to integrate it into their app.

So let's integrate Alan AI voice assistant into a React App.🎉

What we will be building?🤔

We will be building a QuoteBook đź“š React app with Alan AI's voice assistant integration. This QuoteBook project will simply have quotes and we will customize the voice assistant to tell us the quotes of a specific speaker. It will look something like this.

QuoteBook React App

Project setup

  • Create a react app using npx create-react-app command.
npx create-react-app quoteBook
cd quoteBook
Enter fullscreen mode Exit fullscreen mode
  • Run the react app using npm start.
npm start
Enter fullscreen mode Exit fullscreen mode
  • Create components and the file structure should be like this ,

Fil structure for Alan AI integration

  • Now install Alan AI Web SDK to the app, we will be using the npm package to install the dependency.
 npm install @alan-ai/alan-sdk-web 
Enter fullscreen mode Exit fullscreen mode
  • Import alanBtn to your React component
import alanBtn from "@alan-ai/alan-sdk-web";
Enter fullscreen mode Exit fullscreen mode
  • Now let’s add code in the components and App.jsx

App.jsx

import React, { useEffect } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Quote from "./Quote";
import { Quotes } from "./Quotes";
import alanBtn from "@alan-ai/alan-sdk-web";

function App() {

  return (
    <div>
      <Header />
      {Quotes.map((quoteItem, index) => {
        return (
          <Quote
            key={index}
            id={index}
            quote={quoteItem.quote}
            author={quoteItem.author}
          />
        );
      })}
      <Footer />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Header.jsx

import React from "react";

function Header() {
  return (
    <header>
      <h1>QuoteBook</h1>
    </header>
  );
}

export default Header;
Enter fullscreen mode Exit fullscreen mode

Footer.jsx

import React from "react";

function Footer() {
  const year = new Date().getFullYear();
  return (
    <footer>
      <p>Copyright â“’ {year}</p>
    </footer>
  );
}

export default Footer;
Enter fullscreen mode Exit fullscreen mode

Quote.jsx

import React from "react";

function Quote(props) {

  return (
    <div className="quote">
      <div className="box">
        <h1>{props.quote}</h1>
        <p>{props.author}</p>
      </div>
    </div>
  );
}

export default Quote;
Enter fullscreen mode Exit fullscreen mode
  • Now let's add some content and styles

Quotes.js

export const Quotes = [
    {
        id: 1,
        quote: "“The purpose of our lives is to be happy.”",
        author: "— Dalai Lama"
    },
    {
        id: 2,
        quote: "“Life is what happens when you’re busy making other plans.” ",
        author: "— John Lennon"
    },
    {
        id: 3,
        quote: "“Get busy living or get busy dying.” ",
        author: "— Stephen King"
    },
    {
        id: 4,
        quote: "“Many of life’s failures are people who did not realize how close they were to success when they gave up.”",
        author: "– Thomas A. Edison"
    },
    {
        id: 5,
        quote: "“If life were predictable it would cease to be life, and be without flavor.” ",
        author: "– Eleanor Roosevelt"
    },
    {
        id: 6,
        quote: "“The whole secret of a successful life is to find out what is one’s destiny to do, and then do it.” ",
        author: "– Henry Ford"
    },
    {
        id: 7,
        quote: " “In order to write about life first you must live it.” ",
        author: "– Ernest Hemingway"
    },
    {
        id: 8,
        quote: "“The big lesson in life, baby, is never be scared of anyone or anything.”",
        author: "– Frank Sinatra"
    },
    {
        id: 9,
        quote: " “Life is a succession of lessons which must be lived to be understood.”",
        author: " — Helen Keller"
    },
    {
        id: 10,
        quote: "“Be yourself; everyone else is already taken.”",
        author: "― Oscar Wilde"
    },

];
Enter fullscreen mode Exit fullscreen mode

Styles.css

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  /* overflow-y: hidden; */
}
html {
  font-family: "Montserrat", sans-serif;
}
body {
  background: #BDE6F1;
  padding: 0 16px;
  background-image: url("https://www.transparenttextures.com/patterns/always-grey.png");;
}

header {
  background-color: #0AA1DD;
  margin: auto -16px;
  padding: 16px 32px;
  text-align: center;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);
}

header h1 {
  color: #fff;
  font-family: "McLaren", cursive;
  font-weight: 200;
}

footer {
  position: absolute;
  text-align: center;
  bottom: 0;
  width: 100%;
  height: 2.5rem;
}

footer p {
  color: #ccc;
}
.quote {
  background: #fff;
  border-radius: 7px;
  box-shadow: 0 2px 5px #ccc;
  padding: 30px 25px;
  width: 240px;
  height: 240px;
  margin: 20px;
  float: left;
}
.quote div{
  margin: auto;
}
.quote h1 {
  text-align: center;
  font-size: 1.1em;
  margin-bottom: 6px;
}
.quote p {
  text-align: center;
  font-size: 1em;
  margin-bottom: 10px;
  white-space: pre-wrap;
  word-wrap: break-word;
}
Enter fullscreen mode Exit fullscreen mode
  • Add alanBtn to App.js via useEffect.
useEffect(() => {
  alanBtn({
    key: 'YOUR_KEY_FROM_ALAN_STUDIO_HERE',
    onCommand: (commandData) => {
      if (commandData.command === 'go:back') {
        // Call the client code that will react to the received command
      }
    }
  });
}, []);
Enter fullscreen mode Exit fullscreen mode
  • Generate key from Alan Studio

To integrate Alan AI voice assistant into your app, a key will be required. To generate this key head over to Alan Studio and Sign up. You will be redirected to a page that will look like this:

Alan AI project landing page

Click on Create voice assistant, and create an empty project by giving it a name, for this project name it QuoteBook:

Alan AI Project types

There is an Integrations tab in the menu bar on top, click on it. You will find your Alan SDK Key, copy it and paste in your code above the comment.

Till now you have integrated your project with Alan AI voice assistant. Now, let’s add some scripts to customize the voice assistant according to the app.

intent('What does this app do?', 'What can I do here?', 
      reply('This app is your quote book, it keeps a collection of your favourite quotes'));

const CATEGORIES = ['dalai lama','john lennon','stephen king','thomas edison','eleanor roosevelt','henry ford','ernest hemingway','frank sinatra','helen keller','oscar wilde'];
const CATEGORIES_INTENT = `${CATEGORIES.map((category) => `${category}~${category}`).join('|')}`;
intent(`(go to|show|open) (the|) $(C~ ${CATEGORIES_INTENT})`,(p)=>{
        p.play({command:'goto',category:p.C.value.toLowerCase()})
})

intent(`(show|what is|tell me about|what's|what are|what're|read) (the|) $(C~ ${CATEGORIES_INTENT})`,(p)=>{
    if(p.C.value.toLowerCase()=='dalai lama'){
        p.play('The purpose of our lives is to be happy.')
    } else if(p.C.value.toLowerCase()=='john lennon'){
        p.play('Life is what happens when you're busy making other plans.')
    }else if(p.C.value.toLowerCase()=='stephen king'){
        p.play('Get busy living or get busy dying.')
    }else if(p.C.value.toLowerCase()=='thomas edison'){
        p.play('Many of life's failures are people who did not realize how close they were to success when they gave up.')
    }else if(p.C.value.toLowerCase()=='eleanor roosevelt'){
        p.play('If life were predictable it would cease to be life, and be without flavor.')
    }else if(p.C.value.toLowerCase()=='henry ford'){
        p.play('The whole secret of a successful life is to find out what is one's destiny to do, and then do it.')
    }else if(p.C.value.toLowerCase()=='ernest hemingway'){
        p.play('In order to write about life first you must live it.')
    }else if(p.C.value.toLowerCase()=='frank sinatra'){
        p.play('The big lesson in life, baby, is never be scared of anyone or anything.')
    }else if(p.C.value.toLowerCase()=='helen keller'){
        p.play('Life is a succession of lessons which must be lived to be understood.')
    }else if(p.C.value.toLowerCase()=='oscar wilde'){
        p.play('Be yourself; everyone else is already taken.')
    }
})

intent('(go|) back', (p) => {
    p.play('Sure, nice talking to you!');
})

Enter fullscreen mode Exit fullscreen mode

In this script, we are giving the assistant three custom features:

  1. Answer questions like what does this app do?
  2. Tell you the quote by the author’s name
  3. If you say bye, it says nice talking to you!

So this is how you can add a simple voice assistant to your React app.

After this you can test the assistant and further customize it by adding more features to it according to your liking.

Conclusion

Voice assistants can be a great tool to integrate and play around with your apps. It was informative and useful building this QuoteBook React App. Feel free to refer to the entire source code here and explore Alan docs to understand and further develop your application.
Have a great day!🎇

Top comments (0)