メニュー 閉じる

029. Processing for Androidで動画再生アプリを作ってみる

Processing for Androidで動画再生アプリを作ってみます。「data」フォルダ内に再生したい動画を入れ、そのまま一緒にコンパイルして端末にインストールできます。ただ、ステージサイズをsize (1, 1)にしないとダメなのが謎。

import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.app.Activity;
import android.view.ViewGroup;
import android.view.View;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.content.res.Resources;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.Context;

AssetFileDescriptor afd;
Context con;
Activity act;
SurfaceView sfv;
SurfaceHolder sfh;
MediaMetadataRetriever mmr;
MediaPlayer mpl;

void setup () {

	size (1, 1, P2D);

	Looper.prepare ();

	act = this.getActivity ();

	con = act.getApplicationContext ();

	mpl = new MediaPlayer ();

	try {
		afd = con.getAssets ().openFd ("video01.mp4");
		mmr = new MediaMetadataRetriever ();
		mmr.setDataSource (afd.getFileDescriptor (), afd.getStartOffset (), afd.getLength ());
	} catch (IllegalArgumentException e) {
		e.printStackTrace ();
	} catch (IllegalStateException e) {
		e.printStackTrace ();
	} catch (IOException e) {
		e.printStackTrace ();
	}

	sfv = new SurfaceView (act);

	sfh = sfv.getHolder ();
	sfh.setType (SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	sfh.addCallback (
		new SurfaceHolder.Callback () {
			@Override
			public void surfaceCreated (SurfaceHolder surfaceHolder) {
				mpl.setDisplay (surfaceHolder);
			}
			@Override
			public void surfaceChanged (SurfaceHolder surfaceHolder, int i, int i2, int i3) {
				mpl.setDisplay (surfaceHolder);
			}
			@Override
			public void surfaceDestroyed (SurfaceHolder surfaceHolder) {
				mpl.stop ();
			}
		}
	);

	start_video ();

}

void draw () {

}

void on_pause () {

	if (mpl != null) {
		mpl.release ();
		mpl = null;
	}

	super.onPause () ;

}

void on_stop () {

	if (mpl != null) {
		mpl.release ();
		mpl = null;
	}
	
	super.onStop () ;

}

void on_destroy () {

	if (mpl != null) {
		mpl.release ();
		mpl = null;
	}
	
	super.onDestroy () ;

}

void on_resume () {

	super.onResume () ;

}

void start_video () {

	act.runOnUiThread (
		new Runnable () {
			public void run () {
				try {
					mpl.setDataSource (afd.getFileDescriptor (), afd.getStartOffset (), afd.getLength ());
					sfh = sfv.getHolder ();
					sfh.setType (SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
					mpl.prepare ();
					act.addContentView (sfv, new ViewGroup.LayoutParams (720, 1280));
					if (mpl.isPlaying () == false) {
						mpl.setLooping (true);
						mpl.start ();
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace ();
				} catch (IllegalStateException e) {
					e.printStackTrace ();
				} catch (IOException e) {
					e.printStackTrace ();
				}
			}
		}
	);
	
};

 

Posted in android , processing