如何在 Android 中播放 YouTube 视频?

发布于 2024-11-05 05:27:14 字数 860 浏览 1 评论 0原文

我正在使用以下类来播放 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)

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

I'm using the following class to play YouTube video:
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);

It loads the video, but after some time gives an error "Sorry,this video can't be played"

and in log gives an error like below.

-> 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)

I don't understand where what my mistake is. Can any one help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏有森光若流苏 2024-11-12 05:27:14

尝试这样的事情:

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;
    }

Try Something like this:

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;
    }
李不 2024-11-12 05:27:14

HTTP request failed w/ http status 404 是一个页面未找到错误,因此我建议 URL 错误。我尝试了错误中的链接,它是一个空白页。

HTTP request failed w/ http status 404 is a page not found error so I would suggest the URL is wrong. I tried the link in the error and it is a blank page.

晨曦慕雪 2024-11-12 05:27:14

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

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

using embed link i can played the youtube video.

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/embed/"+sn+"?autoplay=1"));
startActivityForResult(i, 0);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文