IOS Android 视频播放(不使用第三方库,使用平台底层sdk)实现

来源:互联网 发布:淘宝上的开团提醒 编辑:程序博客网 时间:2024/05/16 18:46

IOS 的实现步骤如下

1:加入引用头文件,声明对象

//video

#import <MediaPlayer/MediaPlayer.h>

@property (strong,nonatomic) EAGLContext *context;


2:编写播放逻辑


//video----start

-(void) playerVideo

{

    if( [self IsVideoPlaying] )

        return;

    

    NSString*thePath=[[NSBundle mainBundle] pathForResource:@"video" ofType:@"mp4"];

    

    if( thePath == nullptr )

        return;

    

    NSURL*theurl=[NSURL fileURLWithPath:thePath];

    

    if( theurl == nullptr )

        return;

    

    self.m_moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];

    if(self.m_moviePlayer == nullptr)

        return;

    

    self.m_moviePlayer.view.frame=self.view.bounds;

    [self.m_moviePlayer prepareToPlay];

    [self.m_moviePlayer setShouldAutoplay:YES];// And other options you can look through the documentation.

    [self.view addSubview:self.m_moviePlayer.view];

    [self.m_moviePlayer setFullscreen:YES animated:YES];

    self.m_moviePlayer.controlStyle =MPMovieControlStyleNone;

    

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(myMovieFinishedCallback:)

                                                 name:MPMoviePlayerPlaybackDidFinishNotification

                                               object:self.m_moviePlayer];

}


-(void)myMovieFinishedCallback:(NSNotification*)notify

{

    [self stopVideo];

}


-(void)stopVideo

{

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:MPMoviePlayerPlaybackDidFinishNotification

                                                  object:self.m_moviePlayer];

    [self.m_moviePlayer stop];

    [self.m_moviePlayer.view removeFromSuperview];

}


-(bool)IsVideoPlaying

{

    if(self.m_moviePlayer &&self.m_moviePlayer.playbackState == MPMoviePlaybackStatePlaying )

        returntrue;

    returnfalse;

}

//video----end


3:调用函数playVideo 即可,路径播放文件都是固定的,可以根据自己的需要进行调整即可


Android视频播放如下:(使用SurfaceView和MediaPlayer播放视频)

1:编写一个视频播放类(实际上就是对SurfaceView的包装),取名为VideoViewEx,代码如下

package com.yuy.gameins;


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;
import android.graphics.Canvas;
import android.graphics.Matrix;


public class VideoViewEx extends SurfaceView implements 
SurfaceHolder.Callback, 
View.OnTouchListener, 
MediaPlayer.OnPreparedListener, 
MediaPlayer.OnErrorListener, 
MediaPlayer.OnInfoListener,
MediaPlayer.OnCompletionListener 
{
private static final String TAG = "VideoView";

private MediaPlayer mPlayer; // MediaPlayer对象
private Activity gameActivity;
private Uri resUri;
private AssetFileDescriptor fd;
private boolean surfaceCreated;
private OnFinishListener onFinishListener;

private Matrix mForward = new Matrix();  
private Matrix mReverse = new Matrix(); 


public VideoViewEx(Activity context) 
{
super(context);


this.gameActivity = context;


final SurfaceHolder holder = getHolder();
holder.addCallback(this); // 设置回调接口
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // 设置为Buffer类型(播放视频&Camera预览)
setOnTouchListener(this);


mPlayer = new MediaPlayer();
// mPlayer.setDisplay(getHolder()); //此时holder并未创建,不能在此处设置
mPlayer.setScreenOnWhilePlaying(true);


mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnErrorListener(this);
mPlayer.setOnInfoListener(this);
}

public VideoViewEx 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  
    protected void dispatchDraw(Canvas canvas)
{
    } 


@Override
public void surfaceCreated(final SurfaceHolder holder)

 {
surfaceCreated = true;


mPlayer.setDisplay(holder); // 指定SurfaceHolder
try

 {
mPlayer.prepare();

catch (Exception e1)

 {
}
}


@Override
public void surfaceDestroyed(SurfaceHolder holder)

 {
surfaceCreated = false;

if(mPlayer != null)

{
mPlayer.stop();
mPlayer.reset();
}
}


@Override
public void onPrepared(MediaPlayer player)

 {
Log.i(TAG, "onPrepared");


int wWidth = getWidth();
int wHeight = getHeight();


/* 获得视频宽长 */
int vWidth = mPlayer.getVideoWidth();
int vHeight = mPlayer.getVideoHeight();


/* 最适屏幕 */
float wRatio = (float) vWidth / (float) wWidth; // 宽度比
float hRatio = (float) vHeight / (float) wHeight; // 高度比
float ratio = Math.max(wRatio, hRatio); // 较大的比
vWidth = (int) Math.ceil((float) vWidth / ratio); // 新视频宽度
vHeight = (int) Math.ceil((float) vHeight / ratio); // 新视频高度


// 改变SurfaceHolder大小
getHolder().setFixedSize(vWidth, vHeight);
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)

 {
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 onStop()

 {
mPlayer.stop(); // 大概不会调用 MediaPlayer.onCompletion
dispose();
if(onFinishListener != null)
onFinishListener.onVideoFinish();
}

int posttion;
public void onPause()

 {

posttion = mPlayer.getCurrentPosition()-2000;
mPlayer.pause();
}


public void onResume()
{
stop();
// if(surfaceCreated)
// {
// if( posttion > 0 && mPlayer.isPlaying() )
// {
// mPlayer.start();
// mPlayer.seekTo(posttion);
// }
// else
// stop();
// }
}

public interface OnFinishListener {
public void onVideoFinish();
}
}


2:变量声明

//video
VideoViewEx m_videoView;


3:给你的activity 加个重载

public class MainActivity extends Activity implements OnFinishListener{

.......

}

4:重载onVideoFinish 函数

@Override
public void onVideoFinish()
{
((ViewGroup)getWindow().findViewById(android.R.id.content)).removeView(m_videoView);
m_videoView = null;
}

5:编写一个播放的接口

public boolean playVedio( String strName, boolean bAssert )
{
if( m_videoView == null )
{
m_videoView = new VideoViewEx(this);
}
m_videoView.setOnFinishListener(this);


if( bAssert )
{
try 
{
AssetFileDescriptor afd = getAssets().openFd(strName);
m_videoView.setVideo(afd);

catch (IOException e) 
{
e.printStackTrace();
m_videoView = null;
return false;
}
}
else
{
// Uri uri = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.video);
// m_videoView.setVideo(uri);
m_videoView = null;
return false;
}

((ViewGroup)getWindow().findViewById(android.R.id.content)).addView(m_videoView);
setContentView(m_videoView);
m_videoView.setZOrderMediaOverlay(true);
return true;
}


6:完成后,即可调用这个函数进行视频播放

*1:在onResume onPause这里面,自己根据游戏需求调用即可

0 0