Skip to content

How to run python voice recognition script in Java (Android Studio)?

I’ve searched quite a bit on this topic, looking at options like Jython and Chaquopy, but whatever I do, there is always an error.

What I’m looking to do is, when a button on my Android app is clicked, the python script (voice recognition using gTTS API in python) will run.

This is what my code looks like (using Chaquopy):

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.content.res.AssetFileDescriptor;
import com.chaquo.python.*;


public class MainActivity extends AppCompatActivity implements View.OnTouchListener{

    ImageButton AutoCruiseButton;

    protected void onCreate(Bundle savedInstanceState) {

        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(this));

        AutoCruiseButton = (ImageButton) findViewById(; 
        final MediaPlayer beep1 = MediaPlayer.create(this, R.raw.beep1);
        final MediaPlayer mp = new MediaPlayer();

        AutoCruiseButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                stopAndPlay(R.raw.beep1, mp);
                Python python = Python.getInstance();
                PyObject file = python.getModule("voice_recognition");
                PyObject command = file.callAttr("myCommand");

Top-level build file: build.gradle

buildscript {
    repositories {
        maven { url "" }
    dependencies {
        classpath ''
        classpath "com.chaquo.python:gradle:8.0.0"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

allprojects {
    repositories {

task clean(type: Delete) {
    delete rootProject.buildDir

build.gradle (:app):

apply plugin: ''
apply plugin: 'com.chaquo.python'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.myapplication"
                    srcDirs = ["src/main/python"]
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        python {
            buildPython "C:/Users/Alya/AppData/Local/Microsoft/WindowsApps/python3"
            buildPython "python3"
        ndk {
            abiFilters "armeabi-v7a", "x86"

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), ''
    compileOptions {
        targetCompatibility = 1.8
        sourceCompatibility = 1.8


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
} (located in python folder under the Main folder for Android Studio project):

from gtts import gTTS 
import speech_recognition as sr
import playsound
import sys

counter = 0

def myCommand():
    r = sr.Recognizer()
    global counter
    if counter == 0:
    with sr.Microphone() as source:
        counter += 1
        print('I am ready for your next command')
        r.pause_threshold = 1
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
        command = r.recognize_google(audio)
        print('You said ' + command + 'n')

    #loop back in case not understood
    except sr.UnknownValueError:
        print("I didn't hear that")
        command = ""

    return command

#if statements for executing commands
def assistant(command):
    if 'introduce yourself' in command:

I know Chaquopy works since I tested a basic python file and my emulator didn’t crash. Here is the error I get when clicking the button to run the python script:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 26779
    com.chaquo.python.PyException: ModuleNotFoundError: No module named 'gtts'
        at <python>.java.chaquopy.import_override(import.pxi:20)
        at <python>.java.chaquopy.import_override(import.pxi:60)
        at <python>.voice_recognition.<module>(
        at <python>.importlib._bootstrap._call_with_frames_removed(<frozen importlib._bootstrap>:219)
        at <python>.importlib._bootstrap_external.exec_module(<frozen importlib._bootstrap_external>:783)
        at <python>
        at <python>.importlib._bootstrap._load_unlocked(<frozen importlib._bootstrap>:671)
        at <python>.importlib._bootstrap._find_and_load_unlocked(<frozen importlib._bootstrap>:975)
        at <python>.importlib._bootstrap._find_and_load(<frozen importlib._bootstrap>:991)
        at <python>.importlib._bootstrap._gcd_import(<frozen importlib._bootstrap>:1014)
        at <python>.importlib.import_module(
        at <python>.chaquopy_java.Java_com_chaquo_python_Python_getModule(chaquopy_java.pyx:154)
        at com.chaquo.python.Python.getModule(Native Method)
        at com.example.myapplication.MainActivity$9.onClick(
        at android.view.View.performClick(
        at android.view.View.performClickInternal(
        at android.view.View.access$3100(
        at android.view.View$
        at android.os.Handler.handleCallback(
        at android.os.Handler.dispatchMessage(
        at android.os.Looper.loop(
        at java.lang.reflect.Method.invoke(Native Method)
I/Process: Sending signal. PID: 26779 SIG: 9

Any suggestions of how to proceed? I really rather keep my Android app in Java since the interface is already implemented. How can I fix my code so it works with Chaquopy? Or how would I do it in Jython if it is a better alternative?


You’ll have to install gtts, into your app using pip, as described here. The same goes for the other third-party modules you’re using.

Also, you won’t be able to access files on your Windows desktop from an Android app. Instead, include them in your Python source directory and then access them relative to __file__ as described here.

Unfortunately this script will probably encounter other, more difficult problems:

  • You probably won’t be able to access the device’s microphone or speakers from Python code, so you’ll have to use the Android Java APIs instead.
  • As discussed here, recognize_google requires a FLAC converter, which Chaquopy isn’t currently able to support.

Sorry I couldn’t be more helpful.