2014-09-11 50 views
-1

我想在原生Android應用程序中播放YouTube。 這是我的代碼,但我得到了像無法播放此視頻的結果,所以你可以請幫什麼錯誤代碼如何在Android本機應用程序通過視頻視圖播放你管視頻?

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

} 
+0

歡迎來到StackOverflow,我不是一個android開發人員,所以我不能幫你解決你的問題。但是,作爲一般提示,您需要在您的問題中提供更多信息。您已告訴我們您要做什麼,但是我們需要更多有關錯誤的信息。同時發佈你的整個班級是非常無益的。您需要精確地縮小導致問題的原因並只發布問題代碼。 – JamesENL 2014-09-11 07:24:08

+0

它似乎是重複的問題..因爲你新來stackoverflow我認爲你不知道這裏的規則..google與適當的關鍵字,你可以找到解決方案..人們可能會投下重複的問題..快樂的編碼:) – iSwaroop 2014-09-11 07:26:10

回答

0

可能這可以幫助你。

下面的代碼是你的視頻ID前: - 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(); 
} 
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(); 
    } 

我希望它有用you.in我的項目,其工作的罰款。