j2me工具类:声音播放类SoundUtil

用法:
将需要播放的音乐都罗列在name,type数组中,需要的时候像下面这样调用:
SoundUtil sound=new SoundUtil();
sound.start(musicIndex);

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

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.ToneControl;
import javax.microedition.media.control.VolumeControl;


public class SoundUtil {
	
	String[] name={"rank001.mid","rank002.mid","rank003.mid"};
	String[] type={"audio/midi","audio/midi","audio/midi"};//audio/x-wav
	Player p=null;
	VolumeControl vc;
	int level=50;
	SoundUtil(){
		
	}

	private void init(int index){
		InputStream is=this.getClass().getResourceAsStream("/"+name[index]);
		try {
			p=Manager.createPlayer(is, type[index]);
			p.realize();
			p.prefetch();
			p.setMediaTime(0);
			p.setLoopCount(-1);
			vc=(VolumeControl)p.getControl("VolumeControl");
			if(vc!=null)
				vc.setLevel(getLevel());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void play(int index){
		close();
		init(index);
		start();
	}
	public void start(){
		if(p!=null){
			try {
				p.start();
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void stop(){
		if(p!=null){
			try {
				p.stop();
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void rePlay(int index){
		play(index);
	}
	public void close(){
		if(p!=null){
			p.close();
			p=null;
		}
	}
	//增加、减小音量
	public void controlVolume(boolean isHigher) {
		if (vc != null) {
			if (isHigher) {//响
				level += 20;
				if (level > 100)
					level = 100;
			} else {
				level -= 20;
				if (level < 0)
					level = 0;
			}
			vc.setLevel(level);
		}
	}
	
	//静音\非静音
	public void quitVolume(boolean isQuit) {
		if (vc != null){
			if(isQuit){
				vc.setLevel(0);
			}else{
				vc.setLevel(level);
			}
		}
	}
	
	public int getLevel(){
		return level;
	}
	
	//简单的播放一个音调
	public void playTone(){
		try {
			Manager.playTone(ToneControl.C4,1000,100);
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(音乐,vc++)