java编写添加背景⾳乐代码_java代码中简单添加背景⾳乐(亲
测有效)
在做java贪吃蛇游戏课设时,想添加背景⾳乐,⽤了以下很简单的步骤即可完成,亲测有效哦!
调⽤⽅法:
new Thread(()->{while(true) {Data.playMusic();}
}).start();// Lambda表达式html播放音乐代码
//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 = AudioInputStream(new File("D:/mysoft/eclipse/贪吃蛇/music.wav")); //绝对路径AudioFormat aif = Format();
final SourceDataLine sdl;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
sdl = (SourceDataLine) Line(info);
sdl.open(aif);
sdl.start();
FloatControl fc = (FloatControl) Control(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 = ad(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.AudioInputStream(AudioSystem.java:1189)
at com.ywq3.Test.main(Test.java:21)
如果本⽂对您有帮助,可不可以给萌新点⼀个赞,⿎励⼩萌新坚持写博客的热情!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。