日期:2014-05-20  浏览次数:20792 次

J2ME判断一个音乐是否播放完毕

有一个朋友问我如何判断音乐是否播放完毕。小阿哥小想了一下。于是封装了一套API。仅供参考。希望对你有所帮助。

/**
 * @author 小阿哥
 * 
 * */
public interface AgePlayerListener {
	public void Finish();
}

?

import javax.microedition.media.Manager;
import javax.microedition.media.Player;

/**
 * @author 小阿哥
 * 
 * */
public class AgePlayer 
{
	private Player pl;
	private AgePlayerListener Listener;
	public void start(String music)
	{		
		if(pl!=null&&pl.getState()==Player.STARTED)
		{
			return;
		}
		if(Listener==null)
		{
			System.out.println("您没有设置监听器。。请调用setAgeListener()来进行设置。。");
			return;			
		}
		try {
			pl=Manager.createPlayer(this.getClass().getResourceAsStream(music), "audio/midi");
			pl.realize();
			pl.prefetch();
			pl.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
		new Thread()
		{
			public void run()
			{
				while(true)
				{					
					if(pl.getState()==Player.PREFETCHED)
					{
						Listener.Finish();
						break;
					}
					try{
						Thread.sleep(50);
					}catch(Exception ex)
					{						
					}
				}
			}
		}.start();
	}
	public void setAgeListener(AgePlayerListener Listener)
	{
		this.Listener=Listener;		
	}
}

?

import javax.microedition.media.Player;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * @author 小阿哥
 * 
 * */
public class MyMIDlet extends MIDlet 
{

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		// TODO Auto-generated method stub
		
	}

	protected void pauseApp() {
		// TODO Auto-generated method stub
		
	}

	Player pl;
	protected void startApp() throws MIDletStateChangeException {
		// TODO Auto-generated method stub
		AgePlayer player=new AgePlayer();
		player.setAgeListener(new AgePlayerListener() {			
			public void Finish() {
				// TODO Auto-generated method stub
				System.out.println("播放完毕啦。。哈哈。。做自己要处理的东西就可以了哈。。。。");
			}
		});
		player.start("/30.mid");
	}
}

?