简体   繁体   中英

Java: .mp3 audio file streaming from server to client gives UnsupportedAudioFileException

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);
            }
        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM