cocos2d-x之Android播放视频c++代码

来源:互联网 发布:淘宝买到假货怎么投诉 编辑:程序博客网 时间:2024/06/03 15:56

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 class VideoView extends SurfaceView implements SurfaceHolder.Callback, View.OnTouchListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener,MediaPlayer.OnCompletionListener {private static final String TAG = "VideoView";private MediaPlayer mPlayer; private Activity 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 surfaceCreated(final SurfaceHolder holder) {Log.i(TAG, "surfaceCreated");surfaceCreated = true;mPlayer.setDisplay(holder); // 指定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();/* 获得视频宽长 */float vWidth = 640;float vHeight = 960;/* 最适屏幕 */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));para.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 (IOException 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 any person obtaining a copyof this software 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 do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 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);//添加跳过图片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);Drawable d = Drawable.createFromStream(is, "ui_btn_skip.png");btn.setBackgroundDrawable(d);//重新定义跳过图片宽高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));para.leftMargin = (int)(group.getWidth() - newWidth * 1.5);para.topMargin = (int)(group.getHeight() - newHeight * 1.5);para.gravity = android.view.Gravity.RIGHT;btn.setLayoutParams(para); group.addView(btn);//跳过按钮事件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() {@Overridepublic void run() {instance.a(name); }});}}public static void sendMessage(int what)    {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" you need to initialize your instancebool HelloWorldScene::init(){    //////////////////////////////    // 1. super init first    if ( !BaseScene::init() )    {return false;}//设置管理器的父场景LMINS->setParentScene(this);//以登录layer启动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}



0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小孩不想去幼儿园怎么办 宝宝不想上幼儿园怎么办 小孩不爱学英语怎么办 孩子抵触学英语怎么办 初三了英语不好怎么办 孩子入园焦虑怎么办 家长总是说孩子怎么办 幼师打了小朋友怎么办 幼儿园老师欺负孩子怎么办 被老师冷落怎么办豆瓣 不满老师对孩子怎么办 老师总找茬孩子 怎么办 老师总针对孩子怎么办 老师看你不舒服怎么办 高中孩子不爱学习怎么办 孩子太倔不听话怎么办 老师老说孩子怎么办 孩子13不懂礼貌怎么办 老师不重视你 怎么办 我娃好动不听话怎么办 初三娃不听话该怎么办 小孩爱动不听话怎么办 宝宝吃饭讨神怎么办 孩子速度太慢怎么办 一年级做作业慢怎么办 小学三年级数学差怎么办 拼音基础太差怎么办 小孩学拼音差怎么办? 孩子字词基础差怎么办 孩子的语文不好怎么办 数学一直学不好怎么办 小孩数学成绩差怎么办 理科生语文不好怎么办 小学阅读题不好怎么办 如果孩子考不好怎么办 6岁不认识数字怎么办 数学一点都不会怎么办 初一数学太差怎么办 三年级孩子数学差怎么办 三年级孩子数学很差怎么办 初中学习不好高中怎么办