Android includes a comprehensive Media Player to simplify the playback of audio and video.
Multimedia playback in Android is handled by the MediaPlayer class. You can play media stored in application resources, local files, Content Providers, or streamed from a network URL. In each case,
the file format and type of multimedia being played is abstracted from you as a developer.
The Media Player’s management of audio and video files and streams is handled as a state machine. In the most simplistic terms, transitions through the state machine can be described as follows:
- Initialize the Media Player with media to play.
- Prepare the Media Player for playback.
- Start the playback
- Pause or stop the playback prior to its completing.
- Playback complete.
To play a media resource you need to create a new MediaPlayer instance, initialize it with a media
source, and prepare it for playback.
Initializing Audio Content for PlaybackTo play back audio content using the Media Player, you need to create a new Media Player object and set the data source of the audio in question.
To play back audio using the Media Player, you can use the static create method, passing in the application Context and one of the following:
- A resource identifier
- A URI to a local file using the file:// schema
- A URI to an online audio resource as a URL
- A URI to a local Content Provider row
Initializing audio content for playback
Context appContext = getApplicationContext();
MediaPlayer resourcePlayer = MediaPlayer.create(appContext,R.raw.my_audio);
MediaPlayer filePlayer = MediaPlayer.create(appContext,Uri.parse("file:///sdcard/localfile.mp3"));
MediaPlayer urlPlayer = MediaPlayer.create(appContext,Uri.parse("http://site.com/audio/audio.mp3"));
MediaPlayer contentPlayer = MediaPlayer.create(appContext,Settings.System.DEFAULT_RINGTONE_URI);
Alternatively, you can use the setDataSource method on an existing Media Player instance. This method accepts a file path, Content Provider URI, streaming media URL path, or File Descriptor.
When using the setDataSource method it is vital that you call prepare on the Media Player before you
begin playback.
Using setDataSource and prepare to initialize audio playback
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/sdcard/test.3gp");
mediaPlayer.prepare();
In each case, once you’ve finished playback, callrelease on your Media Player object to free the associated resources:
mediaPlayer.release();
Android supports a limited number of simultaneous Media Player objects; not releasing them can cause runtime exceptions when the system runs out of resources.
Preparing for Video Playback
Playback of video content is slightly more involved than audio. To show a video, you must specify a display surface on which to show it. The following sections describe two alternatives for the playback of video content.
The first, using the Video View control, encapsulates the creation of a display surface and allocation and preparation of video content within a Media Player. The second technique allows you to specify your own display surface and manipulate the underlying Media Player instance directly.
Playing Video Using the Video ViewThe simplest way to play back video is to use the VideoView control. The Video View includes a Surface on which the video is displayed and encapsulates and manages a Media Player to manage the video playback.
The Video View supports the playback of local or streaming video as supported by the Media Player
component. Video Views conveniently encapsulate the initialization of the Media Player. To assign a video to play simply call setVideoPath or setVideoUri to specify the path to a local file, or the URI of a ContentProvider or remote video stream:
streamingVideoView.setVideoUri("http://www.mysite.com/videos/myvideo.3gp");
localVideoView.setVideoPath("/sdcard/test2.3gp");
Once initialized, you can control playback using the start, stopPlayback, pause, and seekTo methods. The Video View also includes the setKeepScreenOn method to apply a screen Wake Lock that will prevent the screen from being dimmed while playback is in progress.
Video playback using a Video View
VideoView videoView = (VideoView)findViewById(R.id.surface);
videoView.setKeepScreenOn(true);
videoView.setVideoPath("/sdcard/test2.3gp");
if (videoView.canSeekForward())
videoView.seekTo(videoView.getDuration()/2);
videoView.start();
[ . . . do something . . . ]
videoView.stopPlayback();
Setting up a Surface for Video Playback
The first step to using the Media Player to view video content is to prepare a Surface onto which the
video will be displayed. TheMedia Player requires a SurfaceHolder object for displaying video content,
assigned using the setDisplay method.
Sample layout including a Surface View
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
The Surface View is a wrapper around the Surface Holder object, which in turn is a wrapper around the Surface that is used to support visual updates from background threads.
Surface Holders are created asynchronously, so you must wait until the surfaceCreated handler has been fired before assigning the returned Surface Holder object to the Media Player.
Initializing and assigning a Surface View to a Media Player
public class MyActivity extends Activity implements SurfaceHolder.Callback
{
private MediaPlayer mediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer = new MediaPlayer();
SurfaceView surface = (SurfaceView)findViewById(R.id.surface);
SurfaceHolder holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) { }
}
Initializing Video Content for Playback
Once you have created and assigned the Surface Holder to your Media Player, use the setDataSource method to specify the path, URL, or Content Provider URI of the video resource to play.
As with audio playback, if you’re passing a URL to an online media file, the file must be capable of
progressive download using the RTSP or HTTP protocols.
Once you’ve selected your media source, callprepare to initialize the Media Player in preparation for
playback.
Initializing video for playback using the Media Player
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource("/sdcard/test2.3gp");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}
Multimedia playback in Android is handled by the MediaPlayer class. You can play media stored in application resources, local files, Content Providers, or streamed from a network URL. In each case,
the file format and type of multimedia being played is abstracted from you as a developer.
The Media Player’s management of audio and video files and streams is handled as a state machine. In the most simplistic terms, transitions through the state machine can be described as follows:
- Initialize the Media Player with media to play.
- Prepare the Media Player for playback.
- Start the playback
- Pause or stop the playback prior to its completing.
- Playback complete.
To play a media resource you need to create a new MediaPlayer instance, initialize it with a media
source, and prepare it for playback.
Initializing Audio Content for PlaybackTo play back audio content using the Media Player, you need to create a new Media Player object and set the data source of the audio in question.
To play back audio using the Media Player, you can use the static create method, passing in the application Context and one of the following:
- A resource identifier
- A URI to a local file using the file:// schema
- A URI to an online audio resource as a URL
- A URI to a local Content Provider row
Initializing audio content for playback
Context appContext = getApplicationContext();
MediaPlayer resourcePlayer = MediaPlayer.create(appContext,R.raw.my_audio);
MediaPlayer filePlayer = MediaPlayer.create(appContext,Uri.parse("file:///sdcard/localfile.mp3"));
MediaPlayer urlPlayer = MediaPlayer.create(appContext,Uri.parse("http://site.com/audio/audio.mp3"));
MediaPlayer contentPlayer = MediaPlayer.create(appContext,Settings.System.DEFAULT_RINGTONE_URI);
Alternatively, you can use the setDataSource method on an existing Media Player instance. This method accepts a file path, Content Provider URI, streaming media URL path, or File Descriptor.
When using the setDataSource method it is vital that you call prepare on the Media Player before you
begin playback.
Using setDataSource and prepare to initialize audio playback
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/sdcard/test.3gp");
mediaPlayer.prepare();
In each case, once you’ve finished playback, callrelease on your Media Player object to free the associated resources:
mediaPlayer.release();
Android supports a limited number of simultaneous Media Player objects; not releasing them can cause runtime exceptions when the system runs out of resources.
Preparing for Video Playback
Playback of video content is slightly more involved than audio. To show a video, you must specify a display surface on which to show it. The following sections describe two alternatives for the playback of video content.
The first, using the Video View control, encapsulates the creation of a display surface and allocation and preparation of video content within a Media Player. The second technique allows you to specify your own display surface and manipulate the underlying Media Player instance directly.
Playing Video Using the Video ViewThe simplest way to play back video is to use the VideoView control. The Video View includes a Surface on which the video is displayed and encapsulates and manages a Media Player to manage the video playback.
The Video View supports the playback of local or streaming video as supported by the Media Player
component. Video Views conveniently encapsulate the initialization of the Media Player. To assign a video to play simply call setVideoPath or setVideoUri to specify the path to a local file, or the URI of a ContentProvider or remote video stream:
streamingVideoView.setVideoUri("http://www.mysite.com/videos/myvideo.3gp");
localVideoView.setVideoPath("/sdcard/test2.3gp");
Once initialized, you can control playback using the start, stopPlayback, pause, and seekTo methods. The Video View also includes the setKeepScreenOn method to apply a screen Wake Lock that will prevent the screen from being dimmed while playback is in progress.
Video playback using a Video View
VideoView videoView = (VideoView)findViewById(R.id.surface);
videoView.setKeepScreenOn(true);
videoView.setVideoPath("/sdcard/test2.3gp");
if (videoView.canSeekForward())
videoView.seekTo(videoView.getDuration()/2);
videoView.start();
[ . . . do something . . . ]
videoView.stopPlayback();
Setting up a Surface for Video Playback
The first step to using the Media Player to view video content is to prepare a Surface onto which the
video will be displayed. TheMedia Player requires a SurfaceHolder object for displaying video content,
assigned using the setDisplay method.
Sample layout including a Surface View
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
The Surface View is a wrapper around the Surface Holder object, which in turn is a wrapper around the Surface that is used to support visual updates from background threads.
Surface Holders are created asynchronously, so you must wait until the surfaceCreated handler has been fired before assigning the returned Surface Holder object to the Media Player.
Initializing and assigning a Surface View to a Media Player
public class MyActivity extends Activity implements SurfaceHolder.Callback
{
private MediaPlayer mediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer = new MediaPlayer();
SurfaceView surface = (SurfaceView)findViewById(R.id.surface);
SurfaceHolder holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) { }
}
Initializing Video Content for Playback
Once you have created and assigned the Surface Holder to your Media Player, use the setDataSource method to specify the path, URL, or Content Provider URI of the video resource to play.
As with audio playback, if you’re passing a URL to an online media file, the file must be capable of
progressive download using the RTSP or HTTP protocols.
Once you’ve selected your media source, callprepare to initialize the Media Player in preparation for
playback.
Initializing video for playback using the Media Player
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource("/sdcard/test2.3gp");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}
No comments:
Post a Comment