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

自用记录,亲测可行。 

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;

 

运行,成功植入,完成!

  • 6
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值