|
嵌入式 | Java | 2843 次查看 |
|---|---|---|
|
||
MMAPI是在JSR 135中提出的,增强了Java ME平台对多媒体编程的支持。例如播放音频和视频文件,捕获声音和图像等。目前大多数支持JTWI 1.0的手机都支持了MMAPI。本文介绍如何使用MMAPI播放gif格式的动画。 其实制作动画效果可以有很多办法,例如准备一个图片数组,在程序中不断的切换显示不同的图片,只要时间的间隔设置合理即可出现动画的效果。如果使用MMAPI则可以直接播放gif的动画。其实这和播放视频文件的方法和流程是类似的。 首先我们应该准备一个gif文件,放在能够访问到的位置,且确保这个文件会被打包进jar内。在创建播放器之前应该先确认手机上的MMAPI实现是否支持image/gif格式的播放,如果支持则创建Player,如下。 private void createPlayer(InputStream is){ String[] contents = Manager.getSupportedContentTypes(null); for(int i = 0;i<contents.length;i++){ if(contents[i].toLowerCase().indexOf("image/gif") != -1){ try { player = Manager.createPlayer(is,"image/gif"); player.realize(); } catch (IOException ex) { ex.printStackTrace(); } catch (MediaException ex) { ex.printStackTrace(); } } } } Player创建后,我们需要获得VideoControl,然后将内容渲染到屏幕上,VideoControl提供了两种模式,这里我们使用USE_GUI_PRIMITIVE方式,将返回的Item追加到一个Form中显示。最后调用Player.start()即可播放。注意在退出之前一定要释放Player资源,关闭Player并设置为null。GifPlayer的源码如下: 源程序如下 /* * GifPlayer.java * * Created on 2006年6月21日, 下午7:28 */ package com.j2medev.gif; import java.io.IOException; import java.io.InputStream; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Item; import javax.microedition.media.Manager; import javax.microedition.media.MediaException; import javax.microedition.media.Player; import javax.microedition.media.control.VideoControl; import javax.microedition.midlet.*; /** * * @author ming * @version */ public class GifPlayer extends MIDlet { private Display display = null; private Player player = null; public void startApp() { if(display == null) display = Display.getDisplay(this); Form form = new Form("gif player"); InputStream is = getClass().getResourceAsStream("/a.gif"); createPlayer(is); if(player == null){ form.append("can not play image/gif"); }else{ VideoControl vc = (VideoControl)player.getControl("VideoControl"); if(vc != null){ form.append((Item)vc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE,null)); } } display.setCurrent(form); try { player.start(); } catch (MediaException ex) { ex.printStackTrace(); } } private void createPlayer(InputStream is){ String[] contents = Manager.getSupportedContentTypes(null); for(int i = 0;i<contents.length;i++){ if(contents[i].toLowerCase().indexOf("image/gif") != -1){ try { player = Manager.createPlayer(is,"image/gif"); player.realize(); } catch (IOException ex) { ex.printStackTrace(); } catch (MediaException ex) { ex.printStackTrace(); } } } } public void pauseApp() { } public void destroyApp(boolean unconditional) { if(player != null){ player.close(); player = null; } } } |
||