MMAPI是在JSR 135中提出的,增强了Java ME平台对多媒体编程的支持。例如播放音频和视频文件,捕获声音和图像等。目前大多数支持JTWI 1.0的手机都支持了MMAPI。本文介绍如何使用MMAPI播放gif格式的动画。
其实制作动画效果可以有很多办法,例如准备一个图片数组,在程序中不断的切换显示不同的图片,只要时间的间隔设置合理即可出现动画的效果。如果使用MMAPI则可以直接播放gif的动画。其实这和播放视频文件的方法和流程是类似的。
首先我们应该准备一个gif文件,放在能够访问到的位置,且确保这个文件会被打包进jar内。在创建播放器之前应该先确认手机上的MMAPI实现是否支持image/gif格式的播放,如果支持则创建Player,如下。
Java代码
privatevoidcreatePlayer(InputStream is){
String[] contents = Manager.getSupportedContentTypes(null);
for(inti =0;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();
}
}
}
}
private void createPlayer(InputStream is){
String[] contents = Manager.getSupportedContentTypes(null);
for(int i = 0;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的源码如下:
Java代码
importjava.io.IOException;
importjava.io.InputStream;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.Item;
importjavax.microedition.media.Manager;
importjavax.microedition.media.MediaException;
importjavax.microedition.media.Player;
importjavax.microedition.media.control.VideoControl;
importjavax.microedition.midlet.*;
publicclassGifPlayerextendsMIDlet {
privateDisplay display =null;
privatePlayer player =null;
publicvoidstartApp() {
if(display ==null)
display = Display.getDisplay(this);
Form form =newForm("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();
}
}
privatevoidcreatePlayer(InputStream is){
String[] contents = Manager.getSupportedContentTypes(null);
for(inti =0;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();
}
}
}
}
publicvoidpauseApp() {
}
publicvoiddestroyApp(booleanunconditional) {
if(player !=null){
player.close();
player =null;
}
}
}
(转于http://azi.javaeye.com/blog/177126)