0

I'm trying to run a python script in Java. python script converts speech to text. But, after executing it in java, I get null output. The python script does not have any error and works fine as I run it in the terminal.

I tried "Thread.sleep()" in order to wait for process but It did not help. "SampleHandler" is my java class name.

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))

6
  • Can you check that: location.getFile() + "resources/speech_to_text.py" it is the right path to execute? You can print it to see the result and try to run the exactly line and see it works and outputs. To get errors you would need: BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); Commented Jun 7, 2019 at 12:49
  • Try changing encoding and sample_rate_hertz. It worked for me. client.recongize can return empty list if values are not correct. Commented Jun 7, 2019 at 12:49
  • Also, you can try to get all the outputs doing: while ((s = stdInput.readLine()) != null) { System.out.println(s); } instead the first line. Commented Jun 7, 2019 at 12:50
  • @Brother The path is correct. I tried to get all output lines. It is null. Commented Jun 7, 2019 at 13:02
  • 1
    @pooya thy this answer. they way he is waiting for the process instead of the timeout and executing the python script. stackoverflow.com/a/33267151/3154883 Commented Jun 7, 2019 at 14:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.