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
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。