2021-12-01 android 本地视频播放

code:

package com.example.media_play;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.Window;

public class MainActivity extends Activity {
     private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final SurfaceView sfv = (SurfaceView) findViewById(R.id.sfv);
        SurfaceHolder holder = sfv.getHolder();
        holder.addCallback(new Callback() { 
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mediaPlayer!=null && mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
            }
             
            @Override
            public void surfaceCreated(SurfaceHolder holder) {;
                 mediaPlayer = new MediaPlayer();
                try {
                    AssetFileDescriptor fd = getAssets().openFd("GEM.mp4");
                    mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                    mediaPlayer.prepare();                   
                    mediaPlayer.setDisplay(holder);
                    mediaPlayer.start();
                } catch (Exception e) {
                    e.printStackTrace();}}
            
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width,
                    int height) {
                
            }
        });
        
        
        /*try {
            AssetFileDescriptor fd = getAssets().openFd("GEM.mp4");
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
    }
}

xml:



    


你可能感兴趣的:(2021-12-01 android 本地视频播放)