Cocos2d-x's Android Play video C + + code

Source: Internet
Author: User

Videoview.java

Package Com.uzwan.ddd;import Java.io.filedescriptor;import Java.io.ioexception;import android.app.Activity;import Android.content.res.assetfiledescriptor;import Android.media.mediaplayer;import Android.net.Uri;import Android.util.log;import Android.view.motionevent;import Android.view.surfaceholder;import Android.view.surfaceview;import android.view.view;/** * * @author Yichou * * Create data:2013-4-22 22:19:49 */public clas S Videoview extends Surfaceview implements Surfaceholder.callback, View.ontouchlistener, Mediaplayer.onpreparedlistener, Mediaplayer.onerrorlistener, Mediaplayer.oninfolistener, Mediaplayer.oncompletionlistener {private static final String TAG = "Videoview";p rivate MediaPlayer mPlayer; private Acti Vity gameactivity;private Uri resuri;private assetfiledescriptor fd;private boolean surfacecreated;private Onfinishlistener onfinishlistener;public Videoview (Activity context) {super (context); this.gameactivity = context; Final Surfaceholder holder = Getholder (); HOLDER.ADDCALlback (this); Holder.settype (surfaceholder.surface_type_push_buffers); Setontouchlistener (this); mPlayer = new MediaPlayer (); mplayer.setscreenonwhileplaying (true); Mplayer.setonpreparedlistener (This), Mplayer.setoncompletionlistener (This), Mplayer.setonerrorlistener (this); Mplayer.setoninfolistener (this);} Public Videoview Setonfinishlistener (Onfinishlistener onfinishlistener) {this.onfinishlistener = OnFinishListener; return this;} public void Setvideo (Uri resuri) {This.resuri = resuri;try {Mplayer.setdatasource (gameactivity, Resuri);} catch ( Exception e) {}}public void Setvideo (Assetfiledescriptor fd) {this.fd = fd;try {Mplayer.setdatasource ( Fd.getfiledescriptor (), Fd.getstartoffset (), fd.getlength ());} catch (IOException e) {e.printstacktrace ();}} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width, int height) {} @Overridepublic void Surfac ecreated (final Surfaceholder holder) {log.i (TAG, "surfacecreated"); surfacecreated = True;mplayer.setdisplay (holder); Specify SurfaCeholdertry {if (Resuri! = null) Mplayer.setdatasource (gameactivity, Resuri); else if (FD! = null) {Mplayer.setdatasource ( Fd.getfiledescriptor (), Fd.getstartoffset (), fd.getlength ());}} catch (Exception e) {}try {mplayer.prepare ();} catch (Exception E1) {}mplayer.start ();} @Overridepublic void surfacedestroyed (Surfaceholder holder) {log.i (TAG, "surfacedestroyed"); surfacecreated = False;if (MPlayer! = null) {mplayer.stop (); Mplayer.reset ();}} @Overridepublic void onprepared (MediaPlayer player) {int wwidth = getwidth (); int wheight = GetHeight ();/* Get video width long */float v Width = 640;float Vheight = 960;/* optimal screen */float oriratio = (float) wwidth/(float) wheight; float nowratio = (float) vwidth/(float) vheight;  float newwidth = wwidth; float newheight = wheight; if (Nowratio > Oriratio) {newheight = Wwidth/nowratio;} if (Nowratio < oriratio) {newwidth = Wheight * nowratio;} Android.widget.FrameLayout.LayoutParams para = new android.widget.FrameLayout.LayoutParams ((int) (newwidth), (int) ( newheight));p Ara.gravity = Android.view.gravity.center;this.setlayoutparams (para); Mplayer.seekto (posttion); MPlayer.start ();} private void Dispose () {mplayer.release (); mPlayer = Null;resuri = Null;if (FD! = null) {try {fd.close ();} catch (Ioexcepti On e) {e.printstacktrace ();} FD = null;}} @Overridepublic void Oncompletion (MediaPlayer MP) {log.i (TAG, "oncompletion"); Stop ();//dispose ();//if ( Onfinishlistener = null)//onfinishlistener.onvideofinish ();} @Overridepublic Boolean oninfo (MediaPlayer MP, int what, int extra) {return true;} @Overridepublic Boolean onError (MediaPlayer MP, int what, int extra) {return true;} @Overridepublic boolean OnTouch (View V, motionevent event) {if (event.getaction () = = Motionevent.action_down) {//stop ();} return true;} public void Stop () {mplayer.stop (); Dispose (); if (onfinishlistener! = null) Onfinishlistener.onvideofinish ();} int posttion;public void Pause () {posttion = Mplayer.getcurrentposition (); Mplayer.pause ();} /** */public void Resume () {if (surfacecreated) {Mplayer.start ();} Else {try {if (Resuri! = null) Mplayer.setdatasource (gameactivity, Resuri); else if (FD! = null) {Mplayer.setdatasource ( Fd.getfiledescriptor (), Fd.getstartoffset (), fd.getlength ());}} catch (Exception e) {}}}public interface Onfinishlistener {public void Onvideofinish ();}}



Helloword.java

/****************************************************************************copyright (c) 2010-2011 Cocos2d-x.orghttp://www.cocos2d-x.orgpermission is hereby granted, free of charge, to all person obtaining a copyof this s  Oftware and associated documentation files (the "Software"), to dealin the software without restriction, including without  Limitation the Rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the software, and To permit persons to whom the software isfurnished to doing so, subject to the following conditions:the above copyright Noti Ce and this permission notice shall being included inall copies or substantial portions of the Software.the software is provi DED "As is", without WARRANTY of any KIND, EXPRESS orimplied, including and not LIMITED to the warranties of Merchantabili Ty,fitness for A particular PURPOSE and noninfringement. In NO EVENT shall theauthors or COPYRIGHT holders is liable for any CLAIM, damages OR otherliability, WHETHERIn a ACTION of contract, TORT or OTHERWISE, arising from,out of or in CONNECTION with the software or the use or other DE Alings inthe Software.****************************************************************************/package Com.wenchang.killyou;import Java.io.ioexception;import Java.io.inputstream;import Java.util.Timer;import Java.util.timertask;import Org.cocos2dx.lib.cocos2dxactivity;import Org.cocos2dx.lib.Cocos2dxGLSurfaceView; Import Com.wenchang.killyou.videoview.onfinishlistener;import Android.content.res.assetfiledescriptor;import Android.content.res.assetmanager;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.drawable.bitmapdrawable;import Android.graphics.drawable.drawable;import Android.net.Uri;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.imagebutton;impoRT Android.widget.imageview;public Class Killyou extends cocos2dxactivity implements Onfinishlistener{static KillYou Instance ViewGroup Group;    Videoview videoview;private ImageButton btn = null;private static int msg = 0; protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); instance = This;group = ( ViewGroup) GetWindow (). Getdecorview (); Timer timer = new timer (); TimerTask timertask = new TimerTask () {@Overridepublic void run () {if (killyou.msg > 0) {handler.sendemptymessage ( KILLYOU.MSG); killyou.msg = 0;}};    Timer.schedule (timertask, 0, 20);}    Public Cocos2dxglsurfaceview Oncreateview () {Cocos2dxglsurfaceview Glsurfaceview = new Cocos2dxglsurfaceview (this);        Killyou should create stencil buffer Glsurfaceview.seteglconfigchooser (5, 6, 5, 0, 16, 8);    return glsurfaceview;    } static {system.loadlibrary ("cocos2dcpp"); private void A (String name) {log.i ("", "name=" + name); videoview = new Videoview (this); Videoview.setonFinishlistener (this); try {assetfiledescriptor afd = getassets (). OPENFD (name); Videoview.setvideo (AfD);} catch ( IOException e) {e.printstacktrace ();} Group.addview (Videoview); Videoview.setzordermediaoverlay (true);//Add skip picture Assetmanager am = getresources (). getAssets (); InputStream is = null;try {is = Am.open ("Ui_btn_skip.png");} catch (IOException e) {//TODO auto-generated catch Blocke . Printstacktrace ();} BTN = new ImageButton (this);D rawable d = Drawable.createfromstream (IS, "ui_btn_skip.png"); Btn.setbackgrounddrawable (d );//redefine skip picture width high float wrate = (float) (93.0/640.0), float hrate = (float) (44.0/960.0); float newwidth = Group.getwidth () * Wrate;float newheight = group.getheight () * Hrate;android.widget.framelayout.layoutparams para = new Android.widget.FrameLayout.LayoutParams ((int) (newwidth), (int) (newheight));p ara.leftmargin = (int) (group.getwidth ()-Newwidth * 1.5);p ara.topmargin = (int) (Group.getheight ()-newheight * 1.5);p ara.gravity = Android.view.Gravity.RIGHT ; Btn.setlayoutparams (Para); Group.addview (BTN);//Skip button Event Btn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {// TODO auto-generated Method Stubonvideofinish ();}});} public static void PlayVideo (final String name) {if (instance! = null) {Instance.runonuithread (new Runnable () {@Overridepu Blic void Run () {INSTANCE.A (name);}});}}    public static void SendMessage (int.) {killyou.msg = what; }private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg);    Switch (msg.what) {case 11:log.i ("ABCDEFG", "11"); Instance.a ("Start.mp4"); break;}}; @Overridepublic void Onvideofinish () {Group.removeview (videoview); videoview = Null;group.removeview (BTN); btn = null;}}

HelloWorldScene.cpp

#include "HelloWorldScene.h" #include "layer\loginlayer.h" #include "layer\registerlayer.h" #include "base\ LayerManager.h "USING_NS_CC;    helloworldscene* helloworldscene::create () {Helloworldscene *pret = new Helloworldscene ();        if (PRet && pret->init ()) {pret->autorelease ();    return pRet;        } else {cc_safe_delete (pRet);    return NULL; }}//on "Init" need to initialize your Instancebool helloworldscene::init () {////////////////////////////////1 . Super init first if (! Basescene::init ()) {return false;}    Set Manager's parent scene lmins->setparentscene (this);//log in layer to start Lmins->runwithlayer (Lm::loginlayer);    Cclog ("PLAY video2.mp4");    PlayVideo ("Video2.mp4");    SendMessage (11); return true;} #if (Cc_target_platform = = cc_platform_android) #include "platform/android/jni/jnihelper.h" #endifvoid PlayVideo (        const char *name) {#if (Cc_target_platform = = cc_platform_android) Jnimethodinfo t; if (Jnihelper::getstaticmethOdinfo (T, "com/wenchang/killyou/killyou", "PlayVideo", "(ljava/lang/string;) V"))        {T.env->callstaticvoidmethod (T.classid, T.methodid, T.env->newstringutf (name));        } #endif}void sendMessage (int what) {#if (Cc_target_platform = = cc_platform_android) Jnimethodinfo t; if (Jnihelper::getstaticmethodinfo (t, "com/wenchang/killyou/killyou", "SendMessage", "(        I) (V ")) {T.env->callstaticvoidmethod (T.classid, T.methodid, what); } #endif}



Cocos2d-x's Android Play video C + + code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.