如何在iPhone中播放Youtube视频

时间:2011-04-28 12:29:32

标签: ios ios4 uiwebview media-player

我想在应用程序中在iPhone中播放Youtube视频。我尝试使用MPMoviePlayerController,但没有加载视频。它正在播放我从视频集中加载的视频,但不播放管视频。我还尝试通过将其嵌入UIWebView来播放Youtube视频,但这也是徒劳的。任何人都可以建议我采取一种方法。我正在IOS 4.2中测试它

这是我使用的代码。

mp =  [[MPMoviePlayerController alloc] initWithContentURL:movieURL];

  if ([mp respondsToSelector:@selector(loadState)]) 
  {
    // Set movie player layout
    [mp setControlStyle:MPMovieControlStyleFullscreen];
    [mp setFullscreen:YES];

        // May help to reduce latency
        [mp prepareToPlay];

        // Register that the load state changed (movie is ready)
        [[NSNotificationCenter defaultCenter] addObserver:self 
                       selector:@selector(moviePlayerLoadStateChanged:) 
                       name:MPMoviePlayerLoadStateDidChangeNotification 
                       object:nil];
    }  
  else
  {
    // Register to receive a notification when the movie is in memory and ready to play.
    [[NSNotificationCenter defaultCenter] addObserver:self 
                         selector:@selector(moviePreloadDidFinish:) 
                         name:MPMoviePlayerContentPreloadDidFinishNotification 
                         object:nil];
  }

  // Register to receive a notification when the movie has finished playing. 
  [[NSNotificationCenter defaultCenter] addObserver:self 
                        selector:@selector(moviePlayBackDidFinish:) 
                        name:MPMoviePlayerPlaybackDidFinishNotification 
                        object:nil];

1 个答案:

答案 0 :(得分:8)

在iOS上播放YouTube视频的唯一方法是使用默认的YouTube播放器播放它们。您应该将视频嵌入到uiwebview中,当您点击/单击它时,默认播放器将打开,请参阅此代码以在uiwebview中嵌入视频 -

- (void)embedYouTube:(NSString*)url frame:(CGRect)frame {
 NSString* embedHTML = @"\
    <html><head>\
 <style type=\"text/css\">\
 body {\
 background-color: transparent;\
 color: white;\
 }\
 </style>\
 </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
 width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";
 NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];
 if(videoView == nil) {
    videoView = [[UIWebView alloc] initWithFrame:frame];
    [self.view addSubview:videoView];
 }
 [videoView loadHTMLString:html baseURL:nil];
}