使用 Java (Swing) 在 JPanel/JFrame 中播放 .wav 声音文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2458885/
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-13 08:00:21  来源:igfitidea点击:

Playing a .wav sound file in JPanel/JFrame using Java (Swing)

javaswingfilepathbufferedimagewav

提问by HEADLESS_0NE

I need some code example on how I would use a filepath from a harddrive location to then play a .wav sound file when opened in swing GUI. I don't need it to show a play button, or pause or stop. I just want it to play when I select the 'Sound' option from my 'Files' in my window (I know how to do that already, no need to explain that).

我需要一些关于如何使用来自硬盘位置的文件路径然后在 Swing GUI 中打开时播放 .wav 声音文件的代码示例。我不需要它来显示播放按钮、暂停或停止。我只想在我从窗口中的“文件”中选择“声音”选项时播放它(我已经知道如何做到这一点,无需解释)。

So basically, just how to play a .wav sound file from a filepath (i.e. c:/cake/thereisnone.wav) inside of a JFrame.

所以基本上,就是如何从 JFrame 内的文件路径(即 c:/cake/thereisnone.wav)播放 .wav 声音文件。

And how can I easily apply methods to that sound file afterwards.

以及之后如何轻松地将方法应用于该声音文件。

Also, if anyone knows how to apply methods on a BufferedImage in a JFrame, that would be helpful too.

此外,如果有人知道如何在 JFrame 中的 BufferedImage 上应用方法,那也会很有帮助。

Thank you very much everyone!

非常感谢大家!

采纳答案by John Kane

Suns sound tutorial is really good. I also found this like helpful: http://www.developer.com/java/other/article.php/2173111/Java-Sound-Playing-Back-Audio-Files-using-Java.htmit shows sample code and one way to do it.

太阳的声音教程真的很好。我也发现这很有帮助:http: //www.developer.com/java/other/article.php/2173111/Java-Sound-Playing-Back-Audio-Files-using-Java.htm它显示了示例代码和一个方法来做到这一点。

回答by trashgod

1) See the Sound tutorial's Overview of the Sampled Package.

1) 请参阅声音教程的采样包概述

2) Override paintComponent()in JPanelto call drawImage(); add the panel to the JFrame. See Painting with Fill Objectsfor examples.

2)覆盖paintComponent()JPanel到呼叫drawImage(); 将面板添加到JFrame. 有关示例,请参阅使用填充对象绘画