Different ways of Playing a media file in Android

In this I am going to explain different ways of playing a media file in Android. Media here I mean video files. First of all we need a instance of mediaPlayer.

- Unlike audio files, media files require SurfaceView to play the media file.

- Then we need to implement the interface to SurfaceHolder.Callback. To implement the callback methods in SurfaceHolder.

Note:One common error in beginners is, they will try to start mediaPlayer in onCreate() of the activity. But actually at this time, the surfaceView might not be created. So we need to call mediaPlayer.start() in the callback method of surfaceHolder in onSurfaceCreated()

If the media file is in raw folder of the resources, we can get it through,

- AssetFileDescriptor afd = this.getResources().openRawResourceFd(R.raw.monster);

Here monster is the media file name. The media file can be either .mp4 type or .3gp. We can set this fileDescriptor to mediaPlayer instance through the method, setDataSource()

- mediaplayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());

Then if the file is in SDCard, then we can set the media file to mediPlayer through

- String path = "file:///sdcard/monster.3gp";
- mediaPlayer.setDataSource(path);

Comments

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android

Open Gallery and get the selected image in appplication