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?