[英]Playing sound in a Java Desktop application
How do we play sound (a music file of any format like .wma, .mp3 ) in a Java desktop application? 我们如何在Java桌面应用程序中播放声音(任何格式的音乐文件,如.wma,.mp3)? (not an applet)
(不是小程序)
I have used the following code (taken from another question on Stack Overflow) but it throws an Exception. 我使用了以下代码(取自Stack Overflow的另一个问题),但它引发了异常。
public class playsound {
public static void main(String[] args) {
s s=new s();
s.start();
}
}
class s extends Thread{
public void run(){
try{
InputStream in = new FileInputStream("C:\\Users\\srgf\\Desktop\\s.wma");
AudioStream as = new AudioStream(in); //line 26
AudioPlayer.player.start(as);
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
}
The program when run throws the following Exception: 运行时,该程序引发以下异常:
java.io.IOException: could not create audio stream from input stream
at sun.audio.AudioStream.<init>(AudioStream.java:82)
at s.run(delplaysound.java:26)
Use this library: 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 :-) 希望对每个人有类似的问题有帮助:-)
Hmmm. 嗯 This might look like advertisement for my stuff, but you could use my API here:
这可能看起来像是广告,但您可以在这里使用我的API:
https://github.com/s4ke/HotSound https://github.com/s4ke/HotSound
playback is quite easy with this one. 播放起来很简单。
Alternative: use Java Clips (prebuffering) 替代方法:使用Java剪辑(预缓冲)
... code ...
// specify the sound to play
File soundFile = new File("pathToYouFile");
//this does the conversion stuff for you if you have the correct SPIs installed
AudioInputStream inputStream =
getSupportedAudioInputStreamFromInputStream(new FileInputStream(soundFile));
// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
// due to bug in Java Sound, explicitly exit the VM when
// the sound has stopped.
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
System.exit(0);
}
}
});
// play the sound clip
clip.start();
... code ...
Then you need this method: 然后,您需要此方法:
public static AudioInputStream getSupportedAudioInputStreamFromInputStream(InputStream pInputStream) throws UnsupportedAudioFileException,
IOException {
AudioInputStream sourceAudioInputStream = AudioSystem
.getAudioInputStream(pInputStream);
AudioInputStream ret = sourceAudioInputStream;
AudioFormat sourceAudioFormat = sourceAudioInputStream.getFormat();
DataLine.Info supportInfo = new DataLine.Info(SourceDataLine.class,
sourceAudioFormat,
AudioSystem.NOT_SPECIFIED);
boolean directSupport = AudioSystem.isLineSupported(supportInfo);
if(!directSupport) {
float sampleRate = sourceAudioFormat.getSampleRate();
int channels = sourceAudioFormat.getChannels();
AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
sampleRate,
16,
channels,
channels * 2,
sampleRate,
false);
AudioInputStream convertedAudioInputStream = AudioSystem
.getAudioInputStream(newFormat, sourceAudioInputStream);
sourceAudioFormat = newFormat;
ret = convertedAudioInputStream;
}
return ret;
}
Source for the Clip example (with little changes by me): http://www.java2s.com/Code/Java/Development-Class/AnexampleofloadingandplayingasoundusingaClip.htm Clip示例的源代码(我几乎没有做任何改动): http : //www.java2s.com/Code/Java/Development-Class/AnexampleofloadingandplayingasoundusingaClip.htm
SPIs are added via adding their .jars to the classpath 通过将.jar添加到类路径中来添加SPI
for mp3 these are: 对于mp3,这些是:
Using JavaFX (which is bundled with your JDK) is pretty simple. 使用JavaFX(与JDK捆绑在一起)非常简单。 You will need the following imports:
您将需要以下导入:
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;
import java.nio.file.Paths;
Steps: 脚步:
Initialize JavaFX: 初始化JavaFX:
new JFXPanel();
Create a Media
(sound): 创建
Media
(声音):
Media media = new Media(Paths.get(filename).toUri().toString());
Create a MediaPlayer
to play the sound: 创建一个
MediaPlayer
播放声音:
MediaPlayer player = new MediaPlayer(media);
And play the Media
: 并播放
Media
:
player.play();
You can set the start/stop times as well with MediaPlayer.setStartTime()
and MediaPlayer.setStopTime()
: 您还可以使用
MediaPlayer.setStartTime()
和MediaPlayer.setStopTime()
设置开始/停止时间:
player.setStartTime(new Duration(Duration.ZERO)); // Start at the beginning of the sound file
player.setStopTime(1000); // Stop one second (1000 milliseconds) into the playback
Or, you can stop playing with MediaPlayer.stop()
. 或者,您可以停止使用
MediaPlayer.stop()
播放。
A sample function to play audio: 播放音频的示例功能:
public static void playAudio(String name, double startMillis, double stopMillis) {
Media media = new Media(Paths.get(name).toUri().toString());
MediaPlayer player = new MediaPlayer(media);
player.setStartTime(new Duration(startMillis));
player.setStopTime(new Duration(stopMillis));
player.play();
}
More info can be found at the JavaFX javadoc . 可以在JavaFX javadoc上找到更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.