I'm trying to play audio on rpi from java. I'm building a chatbot so this is for a text2speech part. I've tried directing the sound through aux, hdmi and even usb doesn't change to problem.
For USB audio I tried: this guide
I'm having alot of problems with this. Does anyone know how to play audio (wav or flac) files using rpi in a consistent way?
System information:
- Raspberry Pi 3 model B+
- OS version: Raspbian latest
- Java: 1.8/8
What I've tried that doesn't work:
The normal Java way (works on my machine):
try { final Clip clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class)); clip.addLineListener(new LineListener() { @Override public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) clip.close(); } }); clip.open(AudioSystem.getAudioInputStream(queue.remove())); clip.start(); } catch (Exception e) { e.printStackTrace(); }
What I've tried that semi works:
Starting a process and play through omxplayer or aplay
try { process = Runtime.getRuntime().exec("aplay " + file.getAbsolutePath()); // or omxplayer BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((reader.readLine()) != null) {} System.out.println("waiting"); process.waitFor(120, TimeUnit.SECONDS); // timeout sometimes System.out.println("done waiting"); process.destroy(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }
This works a couple of times and suddenly It stops playing and the process just hangs. Even if I do a killall/kill -9 on the PID and if I try to play from the terminal the same happens at this point. I have to reboot before the audio will play a couple times again. Though I do see that process.destroy() doesn't always kill the process? But besides that I can't really see why this isn't working.
Can anyone shed some light on this and possibly how to get it working?