Chapter 9. Multimedia

Android is a rich multimedia environment. The standard Android load includes music and video players, and most commercial devices ship with these or fancier versions as well as YouTube players and more. The recipes in this chapter show you how to control some aspects of the multimedia world that Android provides.

9.1 Playing a YouTube Video

Marco Dinacci

Problem

You want to play a video from YouTube on your device.

Solution

Given a URI to play the video, create an ACTION_VIEW Intent with it and start a new Activity.

Discussion

Example 9-1 shows the code required to start a YouTube video with an Intent.

Note

For this recipe to work, the standard YouTube application (or one compatible with it) must be installed on the device.

Example 9-1. Starting a YouTube video with an Intent
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String video_path = "http://www.youtube.com/watch?v=opZ69P-0Jbc";
    Uri uri = Uri.parse(video_path);

    // With this line the YouTube application, if installed, will launch immediately.
    // Without it you will be prompted with a list of applications to choose from.
    uri = Uri.parse("vnd.youtube:"  + uri.getQueryParameter("v"));

    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}

The example uses a standard YouTube.com URL. The uri.getQueryParameter("v") is used to extract the video ID from the URI itself; in our example, the ID is opZ69P-0Jbc ...

Get Android Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.