我正在尝试将一个mp3文件从服务器发送到客户端并播放它,但我无法弄清楚如何做到这一点。我一直在看媒体和媒体播放器java类,但仍然不明白它们是如何工作的,或者知道在这种情况下使用它是否正确,因为我不想在程序结束后将音乐存储在计算机上关闭。这是我的第一个问题,所以如果有任何错误,我很抱歉,但我会学习。
服务器代码片段:
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");
}
客户端代码片段:
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);
}
答案 0 :(得分:1)
Java 7从here
定义了一些不错的类String bip = "bip.mp3";
Media hit = new Media(bip);
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
如果您需要非Java 7方法,请按照Andrew所说并使用MP3 SPI。
答案 1 :(得分:-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!");}
}
}
希望这可以帮到你。