太心塞!弄了很久才终于把Java添加背景音乐实现了。不过还是很Happy!
在网上 找了很多都不能成功。最后自己琢磨弄好了
很多只给代码,小白都不知道放在哪,是创建文件还是什么。自己在GitHub上下好简单代码,加上一下文件就行
直接上图好吧
案例1 :飞机大战
分别在根目录下和src最底层目录下加上音乐文件
然后到eclipse里新建工作区,添加刚才的文件夹
新建music.java ,报错就是包名不对,按提示自动改就行,其他别动。
//唯一需要修改的的就是第一句话,其他的不要改
package com.tarena.fly;
import java.io.File;
import java.io.IOException;
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.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Music extends Thread {
private String fileName;
private final int EXTERNAL_BUFFER_SIZE = 524288;
public Music(String wavFile) {
this.fileName = wavFile;
}
@SuppressWarnings("unused")
public void run() {
File soundFile = new File(fileName); // 播放音乐的文件名
if (!soundFile.exists()) {
System.err.println("Wave file not found:" + fileName);
return;
}
while (true) { // 设置循环播放
AudioInputStream audioInputStream = null; // 创建音频输入流对象
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile); // 创建音频对象
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat(); // 音频格式
SourceDataLine auline = null; // 源数据线
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline.getControl(FloatControl.Type.PAN);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
// auline.close();
}
}
}
}
修改main入口函數内容
//背景音乐启动
Music audioPlayWave = new Music("xcdh.wav");// 开音乐 音樂名
audioPlayWave.start();
@SuppressWarnings("unused")
int musicOpenLab = 1;
然後運行成功
案例二:黃金礦工
結束,兩個都成功加入背景音樂,這可能不是最好的方法,但能讓小白加入音樂成功,只爲交作業的我感到很開心。希望能夠幫助大家