Video Playback from a Web Server

As we said, playing video requires more effort than playing audio. To take some of the pain away, Android provides a specialized view control called android.widget.VideoView that encapsulates creating and initializing the MediaPlayer. To play video, you create a VideoView widget and set that as the content of the UI. You then set the path or URI of the video and fire the start() method. Listing 9-4 demonstrates video playback in Android.

Listing 9-4. Playing a Video Using the Media APIs

<?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="">

<VideoView android:id="@+id/videoView" android:layout_width="200px" android:layout_height="200px" android:layout_x="10px" android:layout_y="10px" />

</AbsoluteLayout> ^Override protected void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); this.setContentView(;

videoView = (VideoView)this.findViewByld(; MediaController mc = new MediaController(this); videoView.setMediaController(mc); videoView.setVideoURI(Uri.parse( ""));

//videoView.setVideoURI(Uri.parse("file:///sdcard/movie.mp4")); videoView.requestFocus();

The example in Listing 9-4 demonstrates video playback of a file located on the web at, which means the application running the code will need to request the android.permission.INTERNET permission. All of the playback functionality is hidden behind the VideoView class. In fact, all you have to do is feed the video content to the video player. The user interface of the application is shown in Figure 9-2.

Figure 9-2. The video-playback UI with media controls enabled

As shown in Figure 9-2 and Listing 9-4, you can enable the VideoView with a media controller. You can set the VideoView's media controller by calling setMediaController() to enable the play, pause, and seek-to controls. If you want to manipulate the video programmatically, you can call the start(), pause(), stopPlayback(), and seekTo() methods.

As we mentioned, the example in Listing 9-4 plays a video file from a web server. You can also play local files. For example, a common use case requires video playback of a file located on the SD card. We'll discuss this use case next.

0 0

Post a comment