Reputation: 11
So Im trying to stream an .mp3
file in real time(like spotify) from server to client. The time i run the client i get Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
, i have seen many similar posts but i cant figure out what is wrong, im stuck for days. The example file im trying to receive from server named AllDay.mp3
is 3.8 mb if this can help.
Client
import java.io.*;
import java.net.*;
import javax.sound.sampled.*;
public class AudioClient {
public static void main(String[] args) throws Exception {
// play soundfile from server
System.out.println("Client: reading from 127.0.0.1:6666");
try (Socket socket = new Socket("127.0.0.1", 6666)) {
if (socket.isConnected()) {
InputStream in = new BufferedInputStream(socket.getInputStream());
play(in);
}
}
}
private static synchronized void play(final InputStream in) throws Exception {
AudioInputStream ais = AudioSystem.getAudioInputStream(in);
try (Clip clip = AudioSystem.getClip()) {
clip.open(ais);
clip.start();
Thread.sleep(100); // given clip.drain a chance to start
clip.drain();
}
}
}
Server
import java.io.*;
import java.net.*;
public class AudioServer {
public static void main(String[] args) throws IOException {
File soundFile = new File("C:\\ServerMusicStorage\\AllDay.mp3");
System.out.println("Streaming to client : " + soundFile);
try (ServerSocket serverSocker = new ServerSocket(6666);
FileInputStream in = new FileInputStream(soundFile)) {
if (serverSocker.isBound()) {
Socket client = serverSocker.accept();
OutputStream out = client.getOutputStream();
byte buffer[] = new byte[2048];
int count;
while ((count = in.read(buffer)) != -1)
out.write(buffer, 0, count);
}
}
}
}
Upvotes: 1
Views: 810
Reputation: 4381
The AudioInputStream class does not support MP3.
Consider using JavaFX Media support. https://docs.oracle.com/javase/8/javafx/api/javafx/scene/media/Media.html
Getting a mp3 file to play using javafx
Upvotes: 1