Search code examples
javaftpmp3javasound

Playing a mp3 file in a client program


I'm trying to send a mp3 file from a server to a client and play it but I can't figure out how to do it. I've been looking at the Media and Media Player java classes but still don't understand how they work or know if it's the correct thing to use for this situation since I don't want the music stored on the computer after the program is closed. This is my first question so I'm sorry if there are any mistakes but I will learn.

Server code fragment:

if(number == songNumber)
{
  File song = files[i];

  byte[] bytearray  = new byte [(int)song.length()];
  FileInputStream fin = new FileInputStream(song);
  BufferedInputStream bin = new BufferedInputStream(fin);

  bin.read(bytearray,0,bytearray.length);
  OutputStream os = socket.getOutputStream();
  System.out.println("Sending Files...");

  os.write(bytearray,0,bytearray.length);
  os.flush();
  socket.close();
  bin.close();
  System.out.println("File transfer complete");
}

Client code fragment:

InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("copy.doc");
BufferedOutputStream bos = new BufferedOutputStream(fos);

byte [] bytearray  = new byte [filesize];
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;

do 
{
  bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
  if(bytesRead >= 0) currentTot += bytesRead;
} 
while(bytesRead > -1);
{
  bos.write(bytearray, 0 , currentTot);
}

Solution

  • Java 7 defines some nice classes so from here

    String bip = "bip.mp3";
    Media hit = new Media(bip);
    MediaPlayer mediaPlayer = new MediaPlayer(hit);
    mediaPlayer.play();
    

    If you need a Non-Java 7 method, do as Andrew says and use an MP3 SPI.