JAVA 炸弹人(二)

JAVA音效
JMF,JAVA多媒体框架。用这个框架播放音乐,和视频代码比较简单,只需要引入相关jar,就OK了。本来是想用这个框架的,后来还是用了JDK自带的。
        在把整个项目打成jar运行的时候,资源出现了路径错误,找不到这些音乐资源,如果用流去读这些资源,就可以解决此问题。
        下面是主要代码,音效类和音效管理类:
package util;

 

import java.io.BufferedInputStream;

import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

/***
 * 
 * @author Jack Lei
 * @Time 上午11:51:18 2016年1月13日
 * @desc
 */
public class Music {
	private MusicType type;
	private String filePath;
    private InputStream inputStream;
    private boolean running;
    private final int byteChunkSize = 1024;
    private byte[] muteData;

 
    public Music(MusicType type,String filePath){
        this.type = type;
        running = false;
        muteData = setMuteData();
        this.filePath = filePath;
    }
    
	public void playMusic() {
	try {
		    inputStream= this.getClass().getResourceAsStream(this.filePath);
	        inputStream = new BufferedInputStream(inputStream);
		    AudioInputStream in = AudioSystem.getAudioInputStream(inputStream);
			
	        AudioInputStream din = null;
	        AudioFormat baseFormat = in.getFormat();
	        AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
	                                                    baseFormat.getSampleRate(),
	                                                    16,
	                                                    baseFormat.getChannels(),
	                                                    baseFormat.getChannels() * 2,
	                                                    baseFormat.getSampleRate(),
	                                                    false);
	        din = AudioSystem.getAudioInputStream(decodedFormat, in);
	        stream(decodedFormat, din);
	        in.close();
		} catch (UnsupportedAudioFileException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	 private void stream(AudioFormat targetFormat, AudioInputStream din){
	        try{
	            byte[] data = new byte[byteChunkSize];
	            SourceDataLine line = getLine(targetFormat);
	            if(line != null){
	                line.start();
	                int nBytesRead = 0;
	                while(nBytesRead != -1 ){
	                    nBytesRead = din.read(data, 0, data.length);
	                    if(nBytesRead != -1){
                         line.write(data, 0, nBytesRead);
	                    }
	                    
//	                    while(pause && running){
//	                        wait(15);
//	                    }
	                }
	                line.drain();
	                line.stop();
	                line.close();
	                din.close();
	            }
	        }catch(Exception e){
	            System.err.println("Problem playing audio!");
	            e.printStackTrace();
	        }
	    }
	 
	 private SourceDataLine getLine(AudioFormat audioFormat){
	        SourceDataLine res = null;
	        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
	        
	        try{
	            res = (SourceDataLine) AudioSystem.getLine(info);
	            res.open(audioFormat);
	        }catch(Exception e){
	            System.err.println("Could not get audio line!");
	            e.printStackTrace();
	        }

	        return res;
	    }
 
 
 
    public boolean isPlaying(){
        return running;
    }
    
    public void stop(){
    	this.running =false;
    }
    
    public void play(){
    	this.running = true;
    }
   
 
 
    private byte[] setMuteData(){
        byte[] x = new byte[byteChunkSize];
        for(int i = 0; i < x.length; i++){
            x[i] = 0;
        }

        return x;
    }
 
	/**
	 * @return the muteData
	 */
	public byte[] getMuteData() {
		return muteData;
	}
	/**
	 * @return the byteChunkSize
	 */
	public int getByteChunkSize() {
		return byteChunkSize;
	}

	/**
	 * @return the type
	 */
	public MusicType getType() {
		return type;
	}
	
	
    
	
    
}

/**
 * 
 */
package util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Jack Lei
 * @Time 下午5:33:25 2016年1月11日
 * @desc 
 */
public class MusicManager {
	private static MusicManager instance ;
	private Thread musicThread;
	private static Map<MusicType,Music> musics = new HashMap<MusicType, Music>();
	
	private MusicManager(){
		musics.put(MusicType.BACK_GROUND,new Music(MusicType.BACK_GROUND, "/sound/back_sound.wav"));
		musics.put(MusicType.READY, new Music(MusicType.READY, "/sound/ready.wav"));
		musics.put(MusicType.BOOM, new Music(MusicType.BOOM, "/sound/boom.wav"));
		musics.put(MusicType.MOVE, new Music(MusicType.MOVE, "/sound/move.wav"));
		musics.put(MusicType.SET_BOMB, new Music(MusicType.SET_BOMB, "/sound/setbomb.wav"));
		musics.put(MusicType.WIN, new Music(MusicType.WIN, "/sound/win.wav"));
		musics.put(MusicType.FILE, new Music(MusicType.FILE, "/sound/faile.wav"));
		musics.put(MusicType.GET_ITEM, new Music(MusicType.GET_ITEM, "/sound/getItem.wav"));
		musics.put(MusicType.ENEMY_BOOM, new Music(MusicType.GET_ITEM, "/sound/enemy.wav"));
	}
	
	public static MusicManager getInstance(){
		if(instance == null){
			instance = new MusicManager();
		}
		return instance;
	}
	
	public void run(){
		musicThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
	 
					 while(true){
						 Iterator<Music> musicIterator = musics.values().iterator();
						 while(musicIterator.hasNext()){
							 Music music = musicIterator.next();
							 	if(music.getType() != MusicType.BACK_GROUND){
									 if(music.isPlaying()){
										 music.playMusic();;
										 music.stop();
								 }
							 }
						 
						 }
						 
						 
						 try {
							Thread.sleep(Common.THREAD_SLEEP_TIME);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					 }
			 
			}
		});
		
		musicThread.start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					musics.get(MusicType.BACK_GROUND).playMusic();;
					 
					 try {
						Thread.sleep(Common.THREAD_SLEEP_TIME);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	public  void playerMusic(MusicType type){
		musics.get(type).play();
	}
	
	public void stopMusic(MusicType type){
		musics.get(type).stop();
	}
 
}

源代码:
后续:
这次就没写整个开发过程了,我会在新年假期时,写一个RPG类型,记录整个开发过程,希望自己能完成。哈哈。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值