如何在Android中播放youtube视频?

时间:2011-05-06 14:32:41

标签: android video streaming youtube

我正在使用以下课程播放YouTube视频:
http://keyeslabs.com/joomla/samplecode/introvideoactivity/IntroVideoActivity.java

main Activity contain code:
Intent lVideoIntent = new Intent(null, Uri.parse("ytv:jRB8dQ5kiLg"), youtube1.this, IntroVideoActivity.class);
startActivity(lVideoIntent);

它会加载视频,但过了一段时间会出现错误“抱歉,此视频无法播放”

并在日志中给出如下错误。

-> http://www.youtube.com/get_video?video_id=jRB8dQ5kiLg&t=vjVQa1PpcFPMdWwPOC2JchyOxvrnNsRs1UyVc7gGd5I%3D&fmt=18
-> ERROR/HTTPDataSource(34): HTTP request failed w/ http status 404
-> INFO/AwesomePlayer(34): mConnectingDataSource->connect() returned -1004
-> ERROR/MediaPlayer(541): error (1, -1004)

我不明白我的错误在哪里。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:3)

尝试这样的事情:

public class MainActivity extends Activity {


VideoView mVideoView;
ProgressBar mProgressBar;
ProgressDialog mProgressDialog;
String url, videoUrl;
Uri rstlUrl;
String[] urlRstp;

@Override
protected void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mVideoView=(VideoView)findViewById(R.id.videoView);
    mProgressBar=(ProgressBar)findViewById(R.id.progressBarV);
    videoUrl=getIntent().getExtras().getString("urla");
//from other activity here... videoUrl is sth like : http://www.youtube.com/watch?v=ER9vmhxFucg


    new MyTask().execute(); 


}
public class MyTask extends AsyncTask<Void, Void, Void>
{


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressBar.setVisibility(LinearLayout.VISIBLE);

    }

    @Override
    protected Void doInBackground(Void... params) {
        url=getUrlVideoRTSP(videoUrl);
        rstlUrl=Uri.parse(url);

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);


        mVideoView.setVideoURI(rstlUrl);
       MediaController mc = new MediaController(VODVideoPlayActivity.this);
        mVideoView.setMediaController(mc);
        mVideoView.requestFocus();
        mVideoView.start();          
        mc.show();
        mProgressBar.setVisibility(LinearLayout.GONE);          
    }




}

public static String getUrlVideoRTSP(String urlYoutube)
{
    try
    {
        String gdy = "http://gdata.youtube.com/feeds/api/videos/";
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        String id = extractYoutubeId(urlYoutube);
        URL url = new URL(gdy + id);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        Document doc = documentBuilder.parse(connection.getInputStream());
        Element el = doc.getDocumentElement();
        NodeList list = el.getElementsByTagName("media:content");///media:content
        String cursor = urlYoutube;
        for (int i = 0; i < list.getLength(); i++)
        {
            Node node = list.item(i);
            if (node != null)
            {
                NamedNodeMap nodeMap = node.getAttributes();
                HashMap<String, String> maps = new HashMap<String, String>();
                for (int j = 0; j < nodeMap.getLength(); j++)
                {
                    Attr att = (Attr) nodeMap.item(j);
                    maps.put(att.getName(), att.getValue());
                }
                if (maps.containsKey("yt:format"))
                {
                    String f = maps.get("yt:format");
                    if (maps.containsKey("url"))
                    {
                        cursor = maps.get("url");
                    }
                    if (f.equals("1"))
                        return cursor;
                }
            }
        }
        return cursor;
    }
    catch (Exception ex)
    {
        Log.e("Get Url Video RTSP Exception======>>", ex.toString());
    }
    return urlYoutube;

}

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);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }

答案 1 :(得分:0)

HTTP request failed w/ http status 404是找不到网页的错误,所以我建议网址错误。我在错误中尝试了链接,它是一个空白页面。

答案 2 :(得分:-1)

使用嵌入链接我可以播放YouTube视频。

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/embed/"+sn+"?autoplay=1"));
startActivityForResult(i, 0);