100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Java小游戏中加背景音乐--有图有真相

Java小游戏中加背景音乐--有图有真相

时间:2022-05-25 19:41:33

相关推荐

Java小游戏中加背景音乐--有图有真相

太心塞!弄了很久才终于把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;

然後運行成功

案例二:黃金礦工

結束,兩個都成功加入背景音樂,這可能不是最好的方法,但能讓小白加入音樂成功,只爲交作業的我感到很開心。希望能夠幫助大家

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。