使用 Java 播放音乐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9818155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:04:45  来源:igfitidea点击:

stream music with java

javanetworkingtcpstream

提问by pudelhund

I am currently coding some chat program and now want to play music via a client command like:

我目前正在编写一些聊天程序,现在想通过客户端命令播放音乐,例如:

/music http://somewebsite.com/somesong.mp3

So the link would be sent from the client that sent the song, to the server. The server should then withoutdownloading the song, stream it to every client (they shouldn't download it as well). Problem is, I don't know how to stream mp3's over a TCP based connection.

所以链接将从发送歌曲的客户端发送到服务器。然后服务器应该下载歌曲,将其流式传输到每个客户端(他们也不应该下载它)。问题是,我不知道如何通过基于 TCP 的连接流式传输 mp3。

My question is, if someone could provide me with libraries/tutorials/ideas/code examples of what I need.

我的问题是,是否有人可以为我提供我需要的库/教程/想法/代码示例。

As an alternative directly streaming music from one client's computer would be okay as well. If I (as a client) play a song on my machine (using some music player like VLC or similar) and then type a certain command (maybe /stream), the sounds from my soundcard would be streamed to the server and then to every client logged in.

作为替代,直接从一个客户端的计算机流式传输音乐也可以。如果我(作为客户端)在我的机器上播放一首歌(使用一些音乐播放器,如 VLC 或类似的),然后输入某个命令(可能是/stream),我的声卡中的声音将被流式传输到服务器,然后到每个客户端登录。

It would be awesome if you could provide me with some advice for both, Google didn't really help so far, mainly because I don't quite understand what I should search for.

如果你能为我提供一些建议,那就太棒了,谷歌到目前为止并没有真正帮助,主要是因为我不太明白我应该搜索什么。

Thanks in advance!

提前致谢!

采纳答案by pudelhund

I found a library that does exactly what I want to do: http://www.javazoom.net/javalayer/javalayer.html

我找到了一个完全符合我想要做的库:http: //www.javazoom.net/javalayer/javalayer.html

public void play() {
        String song = "http://www.ntonyx.com/mp3files/Morning_Flower.mp3";
        Player mp3player = null;
        BufferedInputStream in = null;
        try {
          in = new BufferedInputStream(new URL(song).openStream());
          mp3player = new Player(in);
          mp3player.play();
        } catch (MalformedURLException ex) {
        } catch (IOException e) {
        } catch (JavaLayerException e) {
        } catch (NullPointerException ex) {
        }

}

Hope that helps everyone with a similar question :-)

希望能帮助大家有类似的问题:-)

回答by Sambhav

Simplest way could be using a Servlet. Set the content type as "audio/mpeg3". The servlet will stream the bytes and user will be able to play music in his browser.

最简单的方法可能是使用 Servlet。将内容类型设置为“audio/mpeg3”。servlet 将传输字节,用户将能够在他的浏览器中播放音乐。