J2ME音频播放

J2ME音频播放

   今天上午做了一个播放音乐的小程序,代码如下:

import java.io.*;

import javax.microedition.media.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;


public class AudioPlayerMidlet extends MIDlet implements CommandListener,PlayerListener{

	private static final String EDN_OF_MEDIA = null;
	Player p=null;
	private Command play1Command=new Command("paly jar audio",Command.ITEM,2);
	private Command stopCommand=new Command("stop",Command.ITEM,2);
	private Command exitCommand=new Command("exit",Command.EXIT,1); 
	private Form f;
	private Display dis;
	private Ticker ticker;
	
	public AudioPlayerMidlet() {
		// TODO Auto-generated constructor stub
	}

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

	}

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

	}

	protected void startApp() throws MIDletStateChangeException {
		// TODO Auto-generated method stub
		dis=Display.getDisplay(this);
		f=new Form("PlayAudioDemo″)");
		f.addCommand(play1Command);
		f.addCommand(stopCommand);
		f.addCommand(exitCommand);
		f.setCommandListener(this);
		
		ticker=new Ticker("waiting......");
		f.setTicker(ticker);
		
		dis.setCurrent(f);
	}

	public void playJarAudio()
	{
		InputStream is=getClass().getResourceAsStream("/jk.mid");
		try {
			p=Manager.createPlayer(is,"audio/midi");
			p.addPlayerListener(this);
			p.realize();
			p.prefetch();
			p.start();
			System.out.println("start.......");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void commandAction(Command c, Displayable s) {
		// TODO Auto-generated method stub
		if(c==play1Command) 
			playJarAudio();
		if(c==stopCommand)
		{
			try {
				p.stop();
				p.close();
				p=null;
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		if(c==exitCommand)
		{
			try {
				destroyApp(false);
				notifyDestroyed();
			} catch (MIDletStateChangeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

	public void playerUpdate(Player p, String event, Object eventData) {
		// TODO Auto-generated method stub
		if(event==EDN_OF_MEDIA)
		{
			ticker.setString("over");
		}
		if(event==this.STARTED)
		{
			ticker.setString("playing");
		}
		if(event==this.STOPPED)
		{
			ticker.setString("stoped");
		}
	}

}

 说明:由于WTK 2.2 MIDP 2.0 Platform包含的MIDP2.0只是MMAPI的子集,因此,本章示例的运行并不都是运行在WTK 2.2 MIDP 2.0 Platform上,其中有些示例必须运行在一个包含完整MMAPI实现的平台(如Sony Ericssion K750 Platform)上。

          我是用WTK中的模拟器测试的,本程序是可以正常播放音乐的。一开始我播放的是mp3格式,声音播放不出来,整了半天也整不好,后来换成了mid格式的,竟然成功了,可能是我用的WTK模拟器不支持mp3格式的缘故吧!不过我还有一点不是很明白,手机游戏不是在任何手机上都可以播放声音吗,他们是怎样实现的呢?

你可能感兴趣的:(游戏,C++,c,F#,音乐)