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

pooya
  • 155
  • 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())); – Brother Jun 07 '19 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. – Kshitij Saxena Jun 07 '19 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. – Brother Jun 07 '19 at 12:50
  • @Brother The path is correct. I tried to get all output lines. It is null. – pooya Jun 07 '19 at 13:02
  • @KshitijSaxena The python script works fine on the terminal. I also run it in separately in Eclipse and got the right output. – pooya Jun 07 '19 at 13:04
  • 1
    @pooya thy this answer. they way he is waiting for the process instead of the timeout and executing the python script. https://stackoverflow.com/a/33267151/3154883 – Brother Jun 07 '19 at 14:49

0 Answers0