1

I am making an android music player. One of the features of the app is that it can connect to another device via sockets and then stream files over that connection. Right now, I have the app connecting to my computer with a ServerSocket. What I want is to load an mp3 on my laptop, get all the bytes from the file and send them over the socket. Then The android app should play the bytes as they are received. I was able to write all the bytes to an mp3 file on my phone, but I am wondering if there is a way to play the bytes as they come in without having to download it. I'm using a MediaPlayer for playback.

Here is my code on the android app for receiving data.

            Socket socket = new Socket("ip", port);
            out = new DataOutputStream(socket.getOutputStream());


            out.write("0\r\n".getBytes());
            out.flush();

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            InputStream inS = socket.getInputStream();
            String line;

            FileOutputStream newFile = new FileOutputStream(path+"test.mp3");
            byte[] by = new byte[BUFFER_SIZE];
            int read;
            do{
                read = inS.read(by,0,BUFFER_SIZE);
                newFile.write(by,0,read);
           }while(read>0);

And here is my code on the laptop (which is the server side).

       Path path = "path to mp3";
        byte[] b = Files.readAllBytes(path);

        int portNum = 5000;
        ServerSocket ss = new ServerSocket(portNum);

        while(true)
        {
            System.out.println("waiting for connection:");
            Socket clientSocket = ss.accept();
            System.out.println("Got client");

            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            String line = in.readLine();

            DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());


            System.out.println(line);

        byte[] by = new byte[BUFFER_SIZE];
                FileInputStream s = new FileInputStream(path.toString());
                    int rc = s.read(by);

                    while(rc>0)
                    {
                        System.out.println(rc);
                        out.write(by,0,rc);
                        rc = s.read(by,0,BUFFER_SIZE);
                    }
                    s.close();

Is there a way I can create a MediaPlayer and make it's data source the byte array being read in and have it play simultaneously?

E. R. Wang
  • 11
  • 3
  • there is no *direct* way unfortunately. in API 23 there is a new overload of `setDataSource()` introduced, where you can provide your implementation: https://stackoverflow.com/a/34759311/1568530 – Vladyslav Matviienko Apr 05 '18 at 06:46

0 Answers0