How can I play a Youtube video in an iPhone
I wanted to play a Youtube video in the iPhone from within the application. I tried using the MPMoviePlayerController, but was not loading the video. It is playing the video which I loaded from the bundle but not the you tube video. I also tried to play the Youtube video by embedding it in the UIWebView, but that also was in vain. Can anybody suggest me an approach that i should take. i am testing it in the IOS 4.2
This is the code i used.
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:MPMoviePlayerContentPreloadDidFinis开发者_StackOverflowhNotification
object:nil];
}
// Register to receive a notification when the movie has finished playing.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
The only way to play youtube videos on iOS is to play them using default youtube player. You should embed the video in a uiwebview and when you tap/click on it the default player will open refer this code to embed video in 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];
}
精彩评论