如何在iPhone上播放Youtube视频

3
我想在iPhone应用程序内播放YouTube视频。我尝试使用MPMoviePlayerController,但无法加载视频。它可以播放我从bundle中加载的视频,但不能播放YouTube视频。我还尝试通过将其嵌入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个回答

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];
}

嗨,我尝试了这种方法。在4.0版本之前的版本上尝试时它是有效的。现在我在模拟器4.2上尝试了这种方法,但它不起作用。你在4.0以上的任何SDK上使用它时有效吗? - philip abraham
1
这种方法在模拟器上不起作用,只能在 iPhone 设备上使用。 - Saurabh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接