Java给窗口添加MP3格式背景音乐
时间: 2023-06-29 09:18:18 浏览: 139
要在Java窗口中添加MP3格式的背景音乐,可以使用Java音频播放器API。下面是一个示例代码:
```java
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.net.URL;
public class SoundPlayer {
private Clip clip;
public void play(URL audioFilePath) {
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFilePath);
DataLine.Info info = new DataLine.Info(Clip.class, audioStream.getFormat());
clip = (Clip) AudioSystem.getLine(info);
clip.open(audioStream);
clip.start();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
public void stop() {
if (clip != null && clip.isRunning()) {
clip.stop();
clip.close();
}
}
}
```
使用上述代码时,您可以将背景音乐文件的URL作为参数传递给`play`方法。例如:
```java
SoundPlayer player = new SoundPlayer();
URL audioFileUrl = new URL("file:/path/to/your/mp3/file.mp3");
player.play(audioFileUrl);
```
在窗口关闭时,您也应该调用`stop()`方法停止播放。
阅读全文