Java客户端服务器:实时流音频文件

时间:2020-11-10 11:30:31

标签: java file sockets audio streaming

我正在开发基于Spotify的基于客户端-服务器的音乐应用程序。以下是将mp3 audio file发送给我的客户端的代码的唯一简单部分。我想要的是实时将此.mp3音频文件播放给我的客户端 为了实现此目的需要更改什么?

编辑:我在stackoverflow和GitHub上都看过很多类似的帖子,但是我找不到任何解决方案

服务器

public void send_file_to_client(String requested_file) throws IOException {
        FileInputStream fis = null;
        BufferedInputStream bis = null;

        File FILE_TO_SEND = new File("C:\\ServerMusicStorage\\" + requested_file + ".mp3");
        byte[] mybytearray = new byte[(int) FILE_TO_SEND.length()];
        try {
            fis = new FileInputStream(FILE_TO_SEND);
            bis = new BufferedInputStream(fis);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        OutputStream os = null;
        bis.read(mybytearray, 0, mybytearray.length);
        os = connsock.getOutputStream();
        System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
    }

客户

public static void receive_file_from_server(String requested_file) throws IOException {

        File file_to_save = new File("C:\\ClientMusicStorage\\" + requested_file + ".mp3");
        int bytesRead;
        int current = 0;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        byte[] mybytearray = new byte[FILE_SIZE];
        InputStream is = clientSocket.getInputStream();
        fos = new FileOutputStream(file_to_save);
        bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray, 0, mybytearray.length);
        current = bytesRead;

        do {
            bytesRead
                    = is.read(mybytearray, current, (mybytearray.length - current));
            if (bytesRead >= 0) {
                current += bytesRead;
            }
        } while (bytesRead > -1);

        bos.write(mybytearray, 0, current);
        bos.flush();
        System.out.println("File " + requested_file + ".mp3"
                + " downloaded (" + current + " bytes read)");

    }

0 个答案:

没有答案