如何解决Java套接字:实时流音频文件
我正在制作一个基于客户端-服务器的音乐应用程序,以下是将mp3音频文件发送到我的客户端的代码的唯一简单部分。我想要做的是play this .mp3 audio file to my client in real time like spotify
要进行哪些更改才能实现此目标?
编辑:我在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,mybytearray.length);
os = connsock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,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,mybytearray.length);
current = bytesRead;
do {
bytesRead
= is.read(mybytearray,current,(mybytearray.length - current));
if (bytesRead >= 0) {
current += bytesRead;
}
} while (bytesRead > -1);
bos.write(mybytearray,current);
bos.flush();
System.out.println("File " + requested_file + ".mp3"
+ " downloaded (" + current + " bytes read)");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。