1

我想在我的应用程序中播放你的私人频道视频。我可以从应用程序的频道中获取视频,但我希望在我的应用程序中播放视频。有什么方法可以在我的应用中播放 youtube 频道视频。请帮助我这样做。

主要活动.java

package com.blundell.tut.ui.phone;

import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.VideoView;
import com.blundell.tut.R;
import com.blundell.tut.domain.Library;
import com.blundell.tut.domain.Video;
import com.blundell.tut.service.task.GetYouTubeUserVideosTask;
import com.blundell.tut.ui.VideoClickListener;
import com.blundell.tut.ui.widget.VideoGridView;

/**
 * The Activity can retrieve Videos for a specific username from YouTube</br>
 * It then displays them into a list including the Thumbnail preview and the title</br>
 * There is a reference to each video on YouTube as well but this isn't used in this tutorial</br>
 * </br>
 * <b>Note<b/> orientation change isn't covered in this tutorial, you will want to override
 * onSaveInstanceState() and onRestoreInstanceState() when you come to this
 * </br>
 * @author paul.blundell
 */

    public class MainActivity extends Activity implements VideoClickListener 
    {
        // A reference to our list that will hold the video details
        private VideoGridView listView;
        VideoView videoView;
        private static ProgressDialog progressDialog;
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            listView = (VideoGridView) findViewById(R.id.videosListView);
            videoView = (VideoView) findViewById(R.id.video_View);
            // Here we are adding this activity as a listener for when any row in the List is 'clicked'
            // The activity will be sent back the video that has been pressed to do whatever it wants with
            // in this case we will retrieve the URL of the video and fire off an intent to view it
            listView.setOnVideoClickListener(this);
        }

        public void getUserYouTubeFeed(View v)
        {
            new Thread(new GetYouTubeUserVideosTask(responseHandler, "erosentertainment")).start();
        }

        Handler responseHandler = new Handler() 
        {
            public void handleMessage(Message msg) 
            {
                populateListWithVideos(msg);
            };
        };

        private void populateListWithVideos(Message msg) 
        {
            Library lib = (Library) msg.getData().get(GetYouTubeUserVideosTask.LIBRARY);
            listView.setVideos(lib.getVideos());
        }

        @Override
        protected void onStop() 
        {
            responseHandler = null;
            super.onStop();
        }

        protected static String extractYoutubeId(String url) throws MalformedURLException
        {
            String id = null;
            try
            {
                String query = new URL(url).getQuery();
                if (query != null)
                {
                    String[] param = query.split("&");
                    for (String row : param)
                    {
                        String[] param1 = row.split("=");
                        if (param1[0].equals("v"))
                        {
                            id = param1[1];
                        }
                    }
                }
                else
                {
                    if (url.contains("embed"))
                    {
                        id = url.substring(url.lastIndexOf("/") + 1);
                    }
                }

                System.out.println("..................videoid......."+id);
            }
            catch (Exception ex)
            {
                System.out.println("Exception"+ex);
            }
            return id;
        }

        // This is the interface method that is called when a video in the listview is clicked!
        // The interface is a contract between this activity and the listview
        String Videoid;
        @Override
        public void onVideoClicked(Video video) 
        {
            String url=video.getUrl();
            System.out.println(".....video url........."+url);

            try
            {
                Videoid = extractYoutubeId(url);
            } 
            catch (MalformedURLException e1)
            {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try
            {
                Intent intent = new Intent(null, Uri.parse("ytv://"+Videoid), 
                            MainActivity.this, OpenYouTubePlayerActivity.class);

                startActivity(intent);
            }
            catch(ActivityNotFoundException e)
            {
                e.printStackTrace();
                System.out.println("kailash.........."+e);
            }
        }
    }


----------
**GetYouTubeUserVideosTask.java**

package com.example.youtube;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**
 * This is the task that will ask YouTube for a list of videos for a specified user</br>
 * This class implements Runnable meaning it will be ran on its own Thread</br>
 * Because it runs on it's own thread we need to pass in an object that is notified when it has finished
 *
 * @author paul.blundell
 */
public class GetYouTubeUserVideosTask implements Runnable 
{
    // A reference to retrieve the data when this task finishes
    public static final String LIBRARY = "Library";
    // A handler that will be notified when the task is finished
    private final Handler replyTo;
    // The user we are querying on YouTube for videos
    private final String username;

    /**
     * Don't forget to call run(); to start this task
     * @param replyTo - the handler you want to receive the response when this task has finished
     * @param username - the username of who on YouTube you are browsing
     */
    public GetYouTubeUserVideosTask(Handler replyTo, String username) 
    {
        this.replyTo = replyTo;
        this.username = username;
    }

    @Override
    public void run() 
    {
        try 
        {
            // Get a httpclient to talk to the internet
            HttpClient client = new DefaultHttpClient();
            // Perform a GET request to YouTube for a JSON list of all the videos by a specific user
            HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
            // Get the response that YouTube sends back
            HttpResponse response = client.execute(request);
            // Convert this response into a readable string
            String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
            // Create a JSON object that we can use from the String
            JSONObject json = new JSONObject(jsonString);

            // For further information about the syntax of this request and JSON-C
            // see the documentation on YouTube http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html

            // Get are search result items
            JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");

            // Create a list to store are videos in
            List<Video> videos = new ArrayList<Video>();
            // Loop round our JSON list of videos creating Video objects to use within our app
            for (int i = 0; i < jsonArray.length(); i++) 
            {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // The title of the video
                String title = jsonObject.getString("title");
                // The url link back to YouTube, this checks if it has a mobile url
                // if it doesnt it gets the standard url
                String url;
                try 
                {
                    url = jsonObject.getJSONObject("player").getString("mobile");
                }
                catch (JSONException ignore) 
                {
                    url = jsonObject.getJSONObject("player").getString("default");
                }
                // A url to the thumbnail image of the video
                // We will use this later to get an image using a Custom ImageView
                // Found here http://blog.blundell-apps.com/imageview-with-loading-spinner/
                String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");

                // Create the video object and add it to our list
                videos.add(new Video(title, url, thumbUrl));
            }
            // Create a library to hold our videos
            Library lib = new Library(username, videos);
            // Pack the Library into the bundle to send back to the Activity
            Bundle data = new Bundle();
            data.putSerializable(LIBRARY, lib);

            // Send the Bundle of data (our Library) back to the handler (our Activity)
            Message msg = Message.obtain();
            msg.setData(data);
            replyTo.sendMessage(msg);

        // We don't do any error catching, just nothing will happen if this task falls over
        // an idea would be to reply to the handler with a different message so your Activity can act accordingly
        } 
        catch (ClientProtocolException e) 
        {
            Log.e("Feck", e);
        }
        catch (IOException e) 
        {
            Log.e("Feck", e);
        }
        catch (JSONException e) 
        {
            Log.e("Feck", e);
        }
    }
}
4

1 回答 1

0

要在您的 Android 应用中播放 YouTube 视频,请按照以下说明操作: https ://developers.google.com/youtube/android/player/sample-applications

您下载 Google YouTube API: https ://developers.google.com/youtube/android/player/downloads/

在这个 Api 中有很多关于在应用程序中播放 YouTube 视频的示例。您可以播放来自 Activity、Fragment 等的视频。

于 2013-07-16T07:54:09.067 回答