在Java中运行python脚本:为什么我得到空输出?

时间:2019-06-07 12:44:39

标签: java python python-3.x process

我正在尝试在Java中运行python脚本。 python脚本将语音转换为文本。但是,在Java中执行它之后,我得到了空输出。 python脚本没有任何错误,并且在终端上运行时可以正常工作。

我尝试了“ Thread.sleep()”以等待进程,但这没有帮助。 “ SampleHandler”是我的Java类名称。

Java:

try {
    java.net.URL location =  SampleHandler.class.getProtectionDomain().getCodeSource().getLocation();
    Process p = Runtime.getRuntime().exec(location.getFile() + "resources/speech_to_text.py");
    Thread.sleep(8000);
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String ret = "";
    ret = in.readLine();            
    System.out.println(ret);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} 

Python:

import os
import io
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="key.json"
client = speech.SpeechClient()
file_name = os.path.join('audio.wav')
with io.open(file_name, 'rb') as audio_file:
    content = audio_file.read()
    audio = types.RecognitionAudio(content=content)

config = types.RecognitionConfig(
    encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=44100,
    audio_channel_count=2,
    language_code='en-US')

response = client.recognize(config, audio)

for result in response.results:
    print(format(result.alternatives[0].transcript))

0 个答案:

没有答案