DEV Community

Harshit Singh
Harshit Singh

Posted on

A Fully Functional and more than 50 times tested Voice Assistant using Python in Mobile! With Code

Hello Everyone
Today's topic is very helpful for those looking desperately how to make a voice assistant using Python in their mobile phones right away. Also I will give you the data used in each step.

Step 1: Install Termux And Termux:API but not from Google Play Store

So this step is gonna be very simple if I give you the links, so here they are.

Termux : https://f-droid.org/repo/com.termux_118.apk
Termux:API : https://f-droid.org/repo/com.termux.api_51.apk

Run the followong command in Termux upon installation.

pkg update && upgrade
Enter fullscreen mode Exit fullscreen mode
pkg install python espeak termux-api
Enter fullscreen mode Exit fullscreen mode

Data usage: 150mb+ Approx(200mb maybe)

Step 2: Save file to termux

Type the following command in Termux

nano Speak.py
Enter fullscreen mode Exit fullscreen mode

And paste the following code,

#Created by Its Arun Stark on YT
#Modified by ProHarshit
import subprocess

class Speak:
    def __init__(self,engine='espeak'):
        self.engine = engine
        self.rate = 150 #Speed
        self.gender = "m"
        self.type = 3
        self.language = "en-gb" #en-gb for UK, en-us for US, en-in for Indi
        self.pitch = 250 #Pitch
    def say(self,text:str):
        subprocess.Popen([self.engine,"-s",str(self.rate),"-v",self.language+"+"+self.gender+str(self.type),"-p",str(self.pitch),text]).communicate()
Enter fullscreen mode Exit fullscreen mode

*The settings here are customized for a fully robotic voice. You can change *

Press Ctrl then C the X and then press enter.

Data usage: Offline Step

Step 3: Main Code

Now let's move towards the main code.

Import Modules

import subprocess
from Speak import Speak
import datetime
import os
Enter fullscreen mode Exit fullscreen mode

Define Speak Function

def speak(text):
    s = Speak()
    s.say(text)
Enter fullscreen mode Exit fullscreen mode

Note: Keep the files Speak.py and this main file in same directory.

Define Speech Check Function

def checkspeech()
    print("Listening...")
    result = str(subprocess.getoutput("termux-speech-to-text")) 
    print("Recognizing...") 
    print("User said", result)
Enter fullscreen mode Exit fullscreen mode

Define set of commands(inside checkspeech())

Now let's move towards your code recognizing a few commands.
Here is one example:

    if "hello" in result:
        speak("hello")
    if "name" in result:
        speak("my name is jarvis")
Enter fullscreen mode Exit fullscreen mode

The output will come a voice saying hello and it's name respectively

Define loop outside checkspeech()

while True:
    checkspeech()
Enter fullscreen mode Exit fullscreen mode

Data usage: Offline step

So thanks for visiting today's tutorial. Please tell if I missed something.
Stay Tuned
Built with Ansh Yadav(Pro-Ansh)

Top comments (0)