Py学习  »  Python

如何在Android Studio中从Java代码中执行Python代码?

Mike • 5 年前 • 1932 次点击  

我正在用Java构建Android应用程序的Android应用程序。我想使用speech-to-text和text-to-speech以及一些我已经编写的基于机器学习的python程序。 有可能这样做吗?我需要什么样的技术来完成这个任务?

我遇到了各种各样的解决方案,比如使用sl4a、jython、qpython并在服务器上运行python代码。

Execute python script from android App in Java

How to execute Python script from Java code in Android

在Java中从Android应用程序执行python脚本

请举例说明。作为一个例子,如果我想在我的android应用程序中运行以下python代码(使用google语音识别api进行语音到文本转换):

import speech_recognition as sr
r = sr.Recognizer()

with sr.Microphone() as src:
    print("speak....")
    audio = r.listen(src, 2)
    print("over")
try:
    print("you said: "+r.recognize_google(audio))
except:
    print("cannot recognize")

我应该遵循什么步骤?实现这一目标的最佳途径是什么? 提前谢谢你。

编辑一:能不能用 azure服务 ?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40963
 
1932 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Kerlos Bekhit
Reply   •   1 楼
Kerlos Bekhit    6 年前

我一直在用 JEP 作为Java和Python之间的桥梁,我从来没有在Android应用程序上尝试过这种方法,只使用。(在项目的常见问题解答中,他们指出 能够 工作)

private RunOutputModel run(RunInputModel model, String path) throws Exception {

    RunOutputModel retVal = new RunOutputModel();

    try (SharedInterpreter jep = new SharedInterpreter()) {
        jep.eval("import sys");
        jep.eval("sys.path.append('" + path + "')");
        jep.eval("import master_main");
        jep.set("well", model.getWell());
        jep.set("startDate", model.getStartDate());
        jep.set("endDate", model.getEndDate());
        //other vars
        jep.eval("objClass = master_main.master()");
        jep.eval("x = objClass.main(path, well, startDate, endDate,/*vars*/)");
        Object result1 = jep.getValue("x");
        //manager result
        }
    } catch (Exception e) {
        retVal.setStatus(e.getMessage());
        Utils.log("error", e.getMessage(), path);
    }
    return retVal;
}

下面是python:

class master:
def __init__(self):
    self.SETVARIABLES = ''

def main(self, path, well, startDate, endDate):
    #stuff

通过搜索我发现 this 他们甚至有混合源代码应用程序的项目示例(Python和Java)。