1

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);
            }
        }
    }
}
disisa
  • 11
  • 2

1 Answers1

1

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

swpalmer
  • 3,890
  • 2
  • 23
  • 31
  • thank you, i will use this for future functionalities, but for now i need to stream this mp3 file to my client in realtime. i have spent a month searching for it. can you please guide me? – disisa Nov 05 '20 at 18:51
  • If you are not going to use JavaFX, then you will have to add a library to decode the mp3 file prior to playback. Try searching on github for the terms "mp3" and "java". For example, https://github.com/delthas/JavaMP3 might work for you. There's also javazoom/jlayer I think it even exists on the maven repository. – Phil Freihofner Nov 06 '20 at 22:11