The issue
I'm trying to play sound on a Raspberry Pi 3 B+ through Java, but it doesn't work. I have
- Written code (shown below) in IntelliJ, and confirmed that it works on Windows 10.
- Connected speakers to my Raspberry Pi through aux and
- Used
sudo raspi-config
to set audio to "headphones" (the only option). - Confirmed they work with
aplay my-file.wav
.
- Used
- Attempted to run my code (through Gradle) with
gradle run
in the project directory. It displays the text "Playing audio" as expected, but no audio plays. - Tried the advice in this answer and this one and this forum (hence my audio testing above), all to no avail.
My entire code
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException, InterruptedException {
File file = new File("my-file.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(file.getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
System.out.println("Playing audio");
clip.start();
Thread.sleep(10000);
}
}
Other info
I'm connecting to my Pi over SSH from Windows. My java --version
is
openjdk 11.0.12 2021年07月20日
OpenJDK Runtime Environment (build 11.0.12+7-post-Raspbian-2deb10u1)
OpenJDK Server VM (build 11.0.12+7-post-Raspbian-2deb10u1, mixed mode)
My gradle --version
is Gradle 6.8.3
. I'm using Gradle because the real project I'm working on requires it (this one is obviously just a demo).
I'm interested in any solution whatsoever to use Java to play sound. Is there a way to simply have Java call another bit of code that does work?
-
Maybe related: stackoverflow.com/questions/30377129/…prunge– prunge2021年10月21日 22:33:45 +00:00Commented Oct 21, 2021 at 22:33
1 Answer 1
I found a workaround that works for me: replacing all the lines that create and start the AudioInputStream
and Clip
with this one line:
Runtime.getRuntime().exec("aplay my-file.wav");
Note: I have intentionally not marked this answer correct, because it does not solve the issue with AudioInputStream
. It simply sidesteps the problem, by passing the issue of playing audio to the aplay
command in terminal. Thus, it is not a solution, but it might nonetheless be helpful to someone who just wants to play some sound with Java on a pi, no matter how hacky the approach.
Interestingly, I also found that this breaks for any file path with spaces, and I have absolutely no idea why. I tried enclosing the path in single quotes and double quotes, and escaping spaces with backslashes, and all of those together. Nothing worked. Here's a related question without a definitive answer.