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

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();
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}

	@Override
	public void surfaceCreated(final SurfaceHolder holder) {
		Log.i(TAG, "surfaceCreated");

		surfaceCreated = true;

		mPlayer.setDisplay(holder); // 指定SurfaceHolder
		try {
			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();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.i(TAG, "surfaceDestroyed");
		surfaceCreated = false;

		if(mPlayer != null){
			mPlayer.stop();
			mPlayer.reset();
		}
	}

	@Override
	public 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;
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		Log.i(TAG, "onCompletion");

		stop();
		//dispose();

		//if(onFinishListener != null)
			//onFinishListener.onVideoFinish();
	}

	@Override
	public boolean onInfo(MediaPlayer mp, int what, int extra) {
		return true;
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		return true;
	}

	@Override
	public 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.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, 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 IN
THE 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()
		{
			@Override
			public 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 block
			e.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()
		{

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onVideoFinish();
			}}
		);
	}

	public static void playVideo(final String name) {
		if (instance != null) {
			instance.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					instance.a(name);
				}
			});
		}
	}

	public static void sendMessage(int what)
    {
		killYou.msg = what;
    }

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);

			switch (msg.what)
			{
			case 11:
				Log.i("ABCDEFG", "11");
			    instance.a("start.mp4");
				break;
			}
		}
	};

	@Override
	public 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 instance
bool 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"
#endif

void 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
}
时间: 2024-08-05 19:31:30

cocos2d-x之Android播放视频c++代码的相关文章

android 播放视频

播放视频的两种方式: 使用VideoView播放视频(方便,推荐) 使用MediaPlayer和SurfaceView播放视频(早期的方式) 第一种方式: 使用VideoView播放视频的步骤如下: 在界面布局文件中定义VideoView组件,或在程序中创建VideoView组建 调用VideoView的如下两个方法加载指定视频 setVideoPath(String paht):加载path文件所代表的视频 setVideoURI(URI uri):加载uri所对应的视频 调用VideoVIe

Android 播放视频文件

1 package com.example.myvideo2; 2 3 import java.io.File; 4 5 import android.app.Activity; 6 import android.net.Uri; 7 import android.os.Bundle; 8 import android.os.Environment; 9 import android.view.Menu; 10 import android.view.MenuItem; 11 import an

Android 播放视频并获取指定时间的帧画面

最近做的项目要求既能播放视频(类似于视频播放器),又能每隔1s左右获取一帧视频画面,然后对图片进行处理,调查了一周,也被折磨了一周,总算找到了大致符合要求的方法.首先对调查过程中涉及到的方法进行简单介绍,再重点介绍最终所采用的方法,话不多说,进入正题. 一.MediaMetadataRetriever 播放视频并取得画面的一帧,大家最先想到应该都是这个,我同样也最先对它进行了测试,这里使用MediaPlayer进行播放,视频播放界面使用SurfaceView来实现. public class P

.net利用本地播放器播放视频文件代码

前台点击按钮,执行js事件,跳转到后台代码: function funShowVideo(index) {            var iTop = (window.screen.availHeight - 30 - 500) / 2; //获得窗口的垂直位置;            var iLeft = (window.screen.availWidth - 10 - 660) / 2; //获得窗口的水平位置;            window.open("ShowVideo.aspx

Android -- 播放视频的两种形式

1. 采用Intent调用外部播放器进行视频播放 Intent intent = new Intent(Intent.ACTION_VIEW); String type = "video/mp4"; Uri uri = Uri.parse("/sdcard/123.mp4"); intent.setDataAndType(uri, type); startActivity(intent); 2. 播放本地视频 把视频文件放到项目工程的 res/raw 文件下 Vid

Unity3D Android播放视频

http://blog.csdn.net/awnuxcvbn/article/details/17719789 [csharp] view plaincopy using UnityEngine; using System.Collections; public class MovieTest : MonoBehaviour { void Start() { } void OnGUI() { if (GUI.Button(new Rect(0,0,150,80),"播放")) { Ha

请教:Android正播放视频时的解码输出流如何获取?

============问题描述============ Android播放视频,经过解码器解码 获得数据流 再显示到屏幕上.请问这部分数据(解码器解码后的数据流)通过什么方法可以获取?  请教...  先谢谢啦 ============解决方案1============ 你是想录制视频? ============解决方案2============ 引用 3 楼 yu8fei 的回复: Quote: 引用 2 楼 sagittarius1988 的回复: 你是想录制视频? 不是,跟照相机录像机摄

android采用videoView播放视频(包装)

//android播放视频.用法:于androidManifest.xml添加activity, // <activity android:name=".PlayVideo" // android:label="@string/app_name"> // // </activity> //注意资源路径 //调用时: //Intent intent = new Intent(MainActivity.this, PlayVideo.class)

android利用videoView播放视频(已封装)

//android播放视频,使用方法:在androidManifest.xml中添加activity, // <activity android:name=".PlayVideo" // android:label="@string/app_name"> // // </activity> //注意资源路径 //调用时: //Intent intent = new Intent(MainActivity.this, PlayVideo.cla