java代码添加背景音乐(自用)

2025-10-08 17:12:20

自用记录,亲测可行。

java课设,马里奥的小游戏,总觉得没有背景音乐就少了点乐趣,试了很多种添加背景音乐,这个成功了!!

原作链接:

Java小游戏中加背景音乐--有图有真相_一如既往的博客-CSDN博客_java游戏怎么添加背景音乐

注意添加音乐的格式:.wav

新建class :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();

}

}

}

}

找到主函数

添加代码

//背景音乐启动

Music audioPlayWave = new Music("BGM.wav");// 开音乐(冒号里的内容与音乐文件名一致)

audioPlayWave.start();

@SuppressWarnings("unused")

int musicOpenLab = 1;

运行,成功植入,完成!

斗罗大陆:将神祇传承后,神都去了哪里?海神波塞冬太逗了
天天有货:为货主车主打造自己的货运圈