2011-01-31 3 views
0

Так как у меня нет флеш-плеера для воспроизведения видео с самого Youtube, мне нужно воспроизвести его в моем MediaPlayer по умолчанию. Код, который я использовал это следующим образом:Как создать приложение YouTube в моей вкладке Android?

MediaController mc = new MediaController(ctx); 
     setContentView(R.layout.main); 
     vv = (VideoView) findViewById(R.id.VideoView01); 
     try { 

      ur = Uri.parse(Url /*+ "&fmt=18"*/); // "&fmt=18"to convert to mp4 
      System.out.println("Host = " + ur.getHost()); 
      System.out.println("Encoded Path = " + ur.getEncodedPath()); 

      vv.setVideoURI(ur); 
      // vv.setVideoPath("http://www.daily3gp.com/vids/747.3gp"); 
      vv.setMediaController(mc); 
      vv.requestFocus(); 
      vv.start(); 
      mc.show(); 

     } catch (Exception ex) { 
      System.out.println("Exception!!!!!!!!!!!!!!!! " 
        + ex.getMessage()); 
     } 

вещь .... Это становится связь, и когда мы даем ссылку на игрока, он Сэя Это видео не может быть воспроизведен .....

Пожалуйста, помогите !!!!!!!!!!!!

ответ

0
private static void play(String videoId, int format, String encoding, 
     String userAgent, File outputdir, String extension) 
     throws Throwable { 
    log.fine("Retrieving " + videoId); 
    List<NameValuePair> qparams = new ArrayList<NameValuePair>(); 
    qparams.add(new BasicNameValuePair("video_id", videoId)); 
    qparams.add(new BasicNameValuePair("fmt", "" + format)); 
    URI uri = getUri("get_video_info", qparams); 
    System.out.println("************JavaYoutubeDownloade.play() Uri = " 
      + uri.toString()); 
    System.out.println("JavaYoutubeDownloade.play() User Agent = " 
      + userAgent); 
    CookieStore cookieStore = new BasicCookieStore(); 
    HttpContext localContext = new BasicHttpContext(); 
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet(uri); 
    if (userAgent != null && userAgent.length() > 0) { 
     httpget.setHeader("User-Agent", userAgent); 
    } 

    log.finer("Executing " + uri); 
    HttpResponse response = httpclient.execute(httpget, localContext); 
    HttpEntity entity = response.getEntity(); 
    if (entity != null && response.getStatusLine().getStatusCode() == 200) { 
     InputStream instream = entity.getContent(); 
     String videoInfo = getStringFromInputStream(encoding, instream); 
     if (videoInfo != null && videoInfo.length() > 0) { 
      List<NameValuePair> infoMap = new ArrayList<NameValuePair>(); 
      URLEncodedUtils 
        .parse(infoMap, new Scanner(videoInfo), encoding); 
      String downloadUrl = null; 
      filename = videoId; 

      for (NameValuePair pair : infoMap) { 
       String key = pair.getName(); 
       String val = pair.getValue(); 
       log.finest(key + "=" + val); 
       if (key.equals("title")) { 
        filename = val; 
       } else if (key.equals("fmt_url_map")) { 
        String[] formats = commaPattern.split(val); 
        boolean found = false; 
        for (String fmt : formats) { 
         String[] fmtPieces = pipePattern.split(fmt); 
         if (fmtPieces.length == 2) { 
          int pieceFormat = Integer 
            .parseInt(fmtPieces[0]); 
          log.fine("Available format=" + pieceFormat); 
          if (pieceFormat == format) { 
           // found what we want 
           downloadUrl = fmtPieces[1]; 
           found = true; 
           break; 
          } 
         } 
        } 
        if (!found) { 
         log.warning("Could not find video matching specified format, however some formats of the video do exist (use -verbose)."); 
        } 
       } 
      } 

      filename = cleanFilename(filename); 
      if (filename.length() == 0) { 
       filename = videoId; 
      } else { 
       filename += "_" + videoId; 
      } 
      filename += "." + extension; 


      File outputfile = new File(outputdir, filename); 
      if (!outputfile.exists()) { 
       outputfile.createNewFile(); 

      } 
      //downloadedFile = outputdir.getPath() + "/" + filename; 

      if (downloadUrl != null) { 
       downloadWithHttpClient(userAgent, downloadUrl, outputfile); 

      } else { 
       log.severe("Could not find video"); 
      } 
     } else { 
      log.severe("Did not receive content from youtube"); 
     } 
    } else { 
     log.severe("Could not contact youtube: " + response.getStatusLine()); 
    } 
} 

private static void downloadWithHttpClient(String userAgent, 
     String downloadUrl, File outputfile) throws Throwable { 
    HttpGet httpget2 = new HttpGet(downloadUrl); 
    if (userAgent != null && userAgent.length() > 0) { 
     httpget2.setHeader("User-Agent", userAgent); 
    } 

    log.finer("Executing " + httpget2.getURI()); 
    HttpClient httpclient2 = new DefaultHttpClient(); 
    HttpResponse response2 = httpclient2.execute(httpget2); 
    HttpEntity entity2 = response2.getEntity(); 
    if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) { 
     double length = entity2.getContentLength(); 
     if (length <= 0) { 
      // Unexpected, but do not divide by zero 
      length = 1; 
     } 
     InputStream instream2 = entity2.getContent(); 

     System.out.println("Writing " 
       + commaFormatNoPrecision.format(length) + " bytes to " 
       + outputfile); 
     if (outputfile.exists()) { 
      outputfile.delete(); 
     } 

     FileOutputStream outstream = new FileOutputStream(outputfile); 
     try { 
      byte[] buffer = new byte[BUFFER_SIZE]; 
      double total = 0; 
      int count = -1; 
      int progress = 10; 
      long start = System.currentTimeMillis(); 
      while ((count = instream2.read(buffer)) != -1) { 
       total += count; 
       int p = (int) ((total/length) * ONE_HUNDRED); 
       if (p >= progress) { 
        long now = System.currentTimeMillis(); 
        double s = (now - start)/1000; 
        int kbpers = (int) ((total/KB)/s); 
        System.out.println(progress + "% (" + kbpers + "KB/s)"); 
        progress += 10; 
       } 
       outstream.write(buffer, 0, count); 
      } 
      outstream.flush(); 
     } finally { 
      outstream.close(); 
     } 
     System.out.println("Done"); 
    } 
} 

Адрес электронной почты, указанный мной для загрузки, неверен. Теперь он работает ...

1

Как CommonsWare сказал здесь: play-youtube-video-in-webview

Вы не можете показать их внедренные за исключением, возможно на устройствах, которые имеют Flash.

Однако, если вы можете проанализировать информацию о видео YouTube, вы можете создать ACTION_VIEWIntent, который покажет их в приложении YouTube ... для тех устройств Android, на которых установлено приложение YouTube.

Надеюсь, это поможет.

+0

Как получить информацию о видео Youtube ??? ... Вот где я сейчас застрял .... – aTJ

1

попробовать это может быть полезно для U

startActivity (новый Intent (Intent.ACTION_VIEW, Uri.parse ("http://www.youtube.com")));