-->

Python app listening for a keyword. (Like Cortana)

2020-04-19 07:01发布

问题:

I'm trying to make a Python app, which behaves like Alexa, Cortana or Google's "Ok, Google".

I want it to constantly listen for a specific keyword. After it hears the keyword I want it to execute a function.
How can I do this?

回答1:

Take a look at Speech Recognition This is a library that allows speech recognition including Google Cloud Speech API.

Relating to the second part of your question this seems relevant:

How can i detect one word with speech recognition in Python

Once you can listen for a word just call your function.

import speech_recognition as sr

# get audio from the microphone                                                                       
r = sr.Recognizer()                    
keywork = "hello"                                                                
with sr.Microphone() as source:                                                                       
    print("Speak:")                                                                                   
    audio = r.listen(source)   

try:
    if  r.recognize_google(audio)) == keyword:
        myfunction()
except sr.UnknownValueError:
    print("Could not understand audio")
except sr.RequestError as e:
    print("Could not request results; {0}".format(e))

This code was adapted from this tutorial.



回答2:

This will search for your keyword in the entire speech.

import speech_recognition as sr

r = sr.Recognizer()

keyWord = 'joker'

with sr.Microphone() as source:
    print('Please start speaking..\n')
    while True: 
        audio = r.listen(source)
        try:
            text = r.recognize_google(audio)
            if keyWord.lower() in text.lower():
                print('Keyword detected in the speech.')
        except Exception as e:
            print('Please speak again.')

To improve your accuracy, you can even fetch all possible rhyming words and compare.

You can also do a character by character comparison to calculate the match percentage and set a minimum percentage threshold for the comparison success.