在做java贪吃蛇游戏课设时,想添加背景音乐,用了以下很简单的步骤即可完成,亲测有效哦!
参考一位博主的做法(链接https://blog.csdn.net/weixin_43926171/article/details/90739074)
调用方法:
new Thread(()->{while(true) {Data.playMusic();}
}).start();// Lambda表达式
// new Thread(new Runnable() {
//
// @Override
// public void run() {
// while (true) {
// playMusic();
// }
// }
// }).start();// 开启一个线程用来播放音乐
方法体:
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.SourceDataLine;
static void playMusic() {// 背景音乐播放
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("D:/mysoft/eclipse/贪吃蛇/music.wav")); //绝对路径
AudioFormat aif = ais.getFormat();
final SourceDataLine sdl;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(aif);
sdl.start();
FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
// value可以用来设置音量,从0-2.0
double value = 2;
float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
fc.setValue(dB);
int nByte = 0;
final int SIZE = 1024 * 64;
byte[] buffer = new byte[SIZE];
while (nByte != -1) {
nByte = ais.read(buffer, 0, SIZE);
sdl.write(buffer, 0, nByte);
}
sdl.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
注意事项:
若程序报错:
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1189)
at com.ywq3.Test.main(Test.java:21)
异常信息是说,不支持的格式,即该音频文件不支持,得不到该文件的输入流。我用的是wav格式,原来音频文件是mp3,转换成wav时直接改不行,就会报以上错误。明明是wav文件,却报错说不支持该格式,则可能是该wav文件内部格式有错误。安利一个格式转换网站:https://cn.office-converter.com/Convert-to-WAV。我是转换成正确的wav格式就可以播放音乐啦。此处参考了博客http://blog.csdn.net/qq_25827845/article/details/79026786
如果本文对您有帮助,可不可以给萌新点一个赞,鼓励小萌新坚持写博客的热情!