2

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);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ST33L
  • 67
  • 1
  • 9

2 Answers2

1

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.

Community
  • 1
  • 1
Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
-1
import sun.audio.*;
import java.io.*;

public class playsound{
  public static void main(String[] args){
    try {
      FileInputStream fileau=new FileInputStream("D:/01.mid" );
      AudioStream as=new AudioStream(fileau);
      AudioPlayer.player.start(as);
    }
    catch (Exception e) {System.out.println("failed!");}
  }
}

hope this can help you.

vvv214
  • 110
  • 1
  • 8
  • 1
    They clearly want to play an MP3. THis method will only play WAV's and MIDI's as far as I am aware. – Sinkingpoint Mar 14 '13 at 02:57
  • I remember there is some method in java to start local program on clint computer, can you use this? – vvv214 Mar 14 '13 at 02:59
  • that is, to start a local mp3 player to play mp3. If it is not allowed, maybe you need to import a package that plays mp3 music. – vvv214 Mar 14 '13 at 03:00
  • You could call a local program, but that is terrible. There is no guarantee that any one program is available and you can't account for every possible MP3 playing program. – Sinkingpoint Mar 14 '13 at 03:04