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