如何通过视频观看你在Android原生应用中管视频?

时间:2014-09-11 07:20:06

标签: android youtube

我正在尝试在原生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();
    }

}

2 个答案:

答案 0 :(得分:0)

可能这可以帮到你。

此处代码是您的视频代码: - 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();
}

答案 1 :(得分:0)

在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();
    }

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