【问题标题】:How to play You tube video in android native Application through video view?如何通过视频视图在 android 原生应用程序中播放 Youtube 视频?
【发布时间】:2014-11-05 01:08:06
【问题描述】:

我正在尝试在原生 Android 应用中播放 YouTube。 这是我的代码,但我得到了无法播放此视频的结果,所以请您帮忙看看该代码有什么问题

public class Youtubeplay extends AsyncTask<Void, Void, Void> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(MainActivity.this, "",
                "Loading Video wait...", true);
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            String url = "https://www.youtube.com/watch?v=ZA7Kkhv30WA";
            videoUrl = getUrlVideoRTSP(url);
            Log.e("Video url for playing=========>>>>>", videoUrl);
        } catch (Exception e) {
            Log.e("Login Soap Calling in Exception", e.toString());
        }
        return null;
    }

    private String getUrlVideoRTSP(String urlYoutube) {
        // TODO Auto-generated method stub
        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();
            org.w3c.dom.Document doc = documentBuilder.parse(connection
                    .getInputStream());
            Element el = (Element) doc.getDocumentElement();
            NodeList list = ((org.w3c.dom.Document) 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 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;
    }

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

        videoView.setVideoURI(Uri.parse(videoUrl));
        MediaController mc = new MediaController(MainActivity.this);
        videoView.setMediaController(mc);
        videoView.requestFocus();
        videoView.start();
        mc.show();
    }

}

【问题讨论】:

  • 欢迎来到 StackOverflow,我不是 android 开发人员,所以无法帮助您解决问题。但是,作为一般提示,您需要在问题中提供更多信息。您已经告诉我们您正在尝试做什么,但是我们需要更多关于出了什么问题的信息。同时发布您的整个班级也非常无益。您需要准确缩小导致问题的范围,并仅发布问题代码。
  • 这似乎是重复的问题..作为stackoverflow的新手,我认为您不知道这里的规则..使用适当关键字的google,您可以找到解决方案..人们可能会否决重复的问题..快乐编码:)

标签: android youtube


【解决方案1】:

也许这对你有帮助。

这里的代码是你的 videoid ex:- 6HnoB8lD3AE

写入异步任务。

private String getRstpLinks(String code){
String[] urls = new String[3];
String link = "http://gdata.youtube.com/feeds/api/videos/" + code + "?alt=json";
String json = getJsonString(link); // here you request from the server
try {
    JSONObject obj = new JSONObject(json);
    String entry = obj.getString("entry");
    JSONObject enObj = new JSONObject(entry);
    String group = enObj.getString("media$group");
    JSONObject grObj = new JSONObject(group);
    String content = grObj.getString("media$content");
    JSONObject cntObj = new JSONObject(group);
    JSONArray array = grObj.getJSONArray("media$content");
    for(int j=0; j<array.length(); j++){
        JSONObject thumbs = array.getJSONObject(j);
        String url = thumbs.getString("url");
        urls[j] = url;
        Log.d(TAG, url);
        //data.setThumbUrl(thumbUrl);
    }


    Log.v(TAG, content);
} catch (Exception e) {
    Log.e(TAG, e.toString());
    urls[0] = urls[1] = urls[2] = null;
}
return urls[2];

}

getJsonString() 方法。

public static String getJsonString(String url){
Log.e("Request URL", url);
StringBuilder buffer = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet     request = new HttpGet( url );
HttpEntity entity = null;
try {
    HttpResponse response = client.execute(request);

    if( response.getStatusLine().getStatusCode() == 200 ){
        entity = response.getEntity();
        InputStream is = entity.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while( (line = br.readLine() )!= null ){
            buffer.append(line);
        }
        br.close();

    }
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}finally{
    try {
        entity.consumeContent();
    } catch (Exception e) {
        Log.e(TAG, "Exception = " + e.toString() );
    }
}

return buffer.toString();
}

【讨论】:

    【解决方案2】:

    在 mainactivity.java 中调用此代码

    if (savedInstanceState != null) {
                    int loc = savedInstanceState.getInt("Loc");
                    Log.i("Loaction: ", loc + "");
                    uriYouTube = Uri.parse(savedInstanceState.getString("url"));
                    videoView.setVideoURI(uriYouTube);
                    videoView.seekTo(loc);
                    videoView.setOnPreparedListener(new OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            Log.v("onPrepared", "ok");
                            mp.start();
                        }
                    });
                } else {
                    new RTSPUrlTask().execute(model.VideoUrl);
                }
    
    
    
    private class RTSPUrlTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
                String response = getRTSPVideoUrl(urls[0]);
                return response;
            }
    
            @Override
            protected void onPostExecute(String result) {
                startPlaying(result);
            }
    
            public String getRTSPVideoUrl(String urlYoutube) {
                try {
                    String gdy = "http://gdata.youtube.com/feeds/api/videos/";
                    DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder();
                    String id = extractYoutubeId(urlYoutube);
                    URL url = new URL(gdy + id);
                    HttpURLConnection connection = (HttpURLConnection) url
                            .openConnection();
                    Document doc = dBuilder.parse(connection.getInputStream());
                    Element el = doc.getDocumentElement();
                    NodeList list = el.getElementsByTagName("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) {
                    return urlYoutube;
                }
            }
    
            public String extractYoutubeId(String url) throws MalformedURLException {
                String query = new URL(url).getQuery();
                String[] param = query.split("&");
                String id = null;
                for (String row : param) {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v")) {
                        id = param1[1];
                    }
                }
                return id;
            }
        }
    
        void startPlaying(String url) {
            uriYouTube = Uri.parse(url);
            videoView.setVideoURI(uriYouTube);
            videoView.start();
        }
    

    我希望它对你有用。在我的项目中,它工作正常。

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多