【问题标题】:How to play youtube/vimeo video within the application in iPhone如何在 iPhone 的应用程序中播放 youtube/vimeo 视频
【发布时间】:2014-02-01 00:46:50
【问题描述】:

我正在构建一个应用程序,我想在其中播放来自 Youtube、Vimeo、Direct url 等 url 的视频。我正在使用 AVPlayer 制作自定义播放器,以从视频剪辑的直接 url 播放视频(如 www.abc/play.mp4)。但后来我在播放 youtube 和 vimeo 视频时遇到了一个大问题。经过大量搜索后,我发现这些链接在不使用 UIWebview 的情况下无法播放 Youtube 链接:

Play YouTube videos with MPMoviePlayerController instead of UIWebView

Playing video from youtube link without UIWebView

所以我只使用了这段代码:

NSString *youTubeVideoHTML = @"<html><head><style>body{margin:0;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:\'100%%\', height:'200px', videoId:\'%@\', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";

NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];
self.embedded_player_view.mediaPlaybackRequiresUserAction = NO;

[self.embedded_player_view loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

现在,当我从 tableview 中单击 youtube/Vimeo 视频链接时,它会使用默认播放器(即 quicktime 播放器)播放视频。它没有在 UIWebview 框架本身内运行视频。 但我想在屏幕的前半部分显示视频,即我的 UIWebview 框架。这可能吗?

在我的应用中,我可以看到:

点击红色播放按钮时,我可以在 quicktime 播放器中全屏看到视频,如下所示:

但我想在同一个 webView 框架内显示视频,而不是通过快速播放器。它应该像这样播放:

MusicTubePlayTube 也是如此。

或者还有其他方法可以达到同样的效果吗?任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 你有解决这个问题的办法吗?我也在尝试显示来自 youtube、vimeo 的视频并面临同样的问题。提前致谢。
  • 不。为 youtube 提供了一些解决方案,但很抱歉不适用于 vimeo。 @AkbariDipali
  • 好的。感谢您的回复。

标签: ios objective-c youtube uiwebview vimeo


【解决方案1】:

如果你想玩 youtube,这里是 github 上的 youtube player project 的链接,它真的很有帮助。是的,可以在你的 uiwebview 中播放它,只需给 webview 的 url 并告诉它加载,它不应该在默认播放器中打开,至少我相信。

【讨论】:

  • 好的,检查一下。并在几分钟内让您知道状态。
  • 不,它再次在默认播放器中打开。不在 webview 框架中。
【解决方案2】:

对于 Vimeo 播放器,您可以查看此链接 https://github.com/lilfaf/YTVimeoExtractor 它在真实播放器中播放视频,如果您想在 uiwebview 中运行视频,这里是该 https://stackoverflow.com/a/15918011/1865424 的代码。

在“urlStr”中传递 YouTube 视频的 URL。

//In .h file
UIWebView *videoView;
// In .m file

videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 385)];

[self embedYouTube :urlStr  frame:CGRectMake(0, 0, 320, 385)];

[self.view addSubview:videoView];

// methos to embed URL in HTML & load it to 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];

}

礼貌:- http://nanostuffs.com/Blog/?p=641

希望这会对您有所帮助。 如果这对您没有帮助,请查看以下链接:-

http://blog.softwareispoetry.com/2010/03/how-to-play-youtube-videos-in-your.html

https://gist.github.com/darkredz/5334409

http://maniacdev.com/2012/02/open-source-library-for-easily-playing-a-youtube-video-in-an-mpmovieplayer

【讨论】:

  • 没有什么对我有帮助。
  • 还没有。 @popeye
  • @Avijit 您可以查看此链接以获取 vimeo..stackoverflow.com/a/14643632/1865424 如果仍然无法使用,请告诉我。
  • 当我使用你的 vimeo 链接时,它只是使用 iPhone 中的默认播放器播放,而不是在 webview 中(如我所料)。没有任何有用的方式在 webview 中播放视频:( .
  • @Avijit 我已经删除了某个时间后的 URL ..你从这里下载它..sendspace.com/file/jyl7lj
【解决方案3】:

我为此使用了this class

您在UIViewController 中看到的视频可以按当前大小播放。

这是我用过的唯一代码:

UIView *videoContainerView = [[UIView alloc]initWithFrame:CGRectMake(0, 50, 320, 200)];
    [self.view addSubview:videoContainerView];        
    XCDYouTubeVideoPlayerViewController *videoPlayerViewController = [[XCDYouTubeVideoPlayerViewController alloc] initWithVideoIdentifier:@"_OBlgSz8sSM"];
    [videoPlayerViewController presentInView:videoContainerView];
    [videoPlayerViewController.moviePlayer play];

【讨论】:

  • 告诉我一件事。这是否违反了 YouTube 的政策?
  • @Avijit 我从不费心阅读 YouTube 政策。我现在在 AppStore 中有一些使用上述内容的应用程序,所以如果有问题,苹果似乎并不介意。
  • @Avijit 我不知道。我只将它用于 youtube。
  • 实际上有 youtube 和 vimeo 的歌曲列表。我必须两个都玩。
  • 搜索栏没有显示在那里。我只能在播放器中看到播放按钮和全屏图标。但是没有你在图片中显示的搜索栏,也没有总时间和进度时间。
【解决方案4】:

我不了解 Vimeo,但对于 youtube 视频,您可以使用 HCYouTubeParser 获取 youtube 视频的 mp4 网址,以后可以根据要求在 AVPlayer 或 MpMoviePlayerVC 上播放。

【讨论】:

    【解决方案5】:

    我在我的项目中使用了 youtube 和 vimeo,我为你分享了我的编码,这对你很有希望

    在我看来controller.m

    //Button action
    
    - (IBAction)importAudioClip:(id)sender
    {
    flag = 0;
    customActionSheet = [[UIActionSheet alloc]initWithTitle:@"Select Audio/Video from:" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"YouTube",@"Vimeo", nil];
    [customActionSheet showInView:self.view];
    
    }
    
    
    #pragma ActionSheet Delegate Methods
    -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
    {
      NSLog(@"CLiekc button is %i",buttonIndex);
    
     if([actionSheet.title isEqualToString:@"Select Audio/Video from:"])
        {
            if (buttonIndex == 0)
            {
                videoStatus=0;
    
                webView.hidden = NO;
    
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.youtube.com"]]];
                NSLog(@"Taking from Youtube");
    
            }
            else if (buttonIndex == 1)
            {
                videoStatus=1;
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"Vimeo" message:@"Please enter Vimeo Username" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
                alertView.tag=123;
                alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
                [alertView show];
    
            }
        }
    }
    
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
    if (alertView.tag==123)
        {
        if (buttonIndex==1)
        {
            templateText=[[UITextField alloc]init];
            templateText = [alertView textFieldAtIndex:0];
            templateText.autocapitalizationType=UITextAutocapitalizationTypeWords;
            templateText.delegate=self;
            if ([templateText.text length]!=0)
            {
                NSString *str=[templateText.text capitalizedString];
                NSLog(@"Str== %@",str);
                [self getVimeoDetails:str];
    
            }
        }
    }
    }
    
    
    -(void)getVimeoDetails:(NSString*)userName
    {
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://vimeo.com/api/v2/%@/videos.json",userName]]];
    [request setHTTPMethod:@"GET"];
    NSError *err;
    NSURLResponse *response;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
    NSLog(@"The value is==%@",resSrt);
    vimeoDetailsArray =(NSArray*) [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
    NSLog(@"jsonObject== %i",[vimeoDetailsArray count]);
    NSString *theReply = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding: NSASCIIStringEncoding];
    NSLog(@"the reply == %@",theReply);
    if(response)
    {
        if (vimeoDetailsArray==NULL)
        {
            NSLog(@"its Null");
            NSLog(@"null response== %@",response);
            //                     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert!!!" message:[NSString stringWithFormat:@"%@",theReply] delegate:self
            //                                                        cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            //                     [alert show];
            // [self performSelector:@selector(showAlertMessage:theReply withTitle:@"Alert!!!") withObject:nil afterDelay:5];
            vimeoVideoTable.hidden=YES;
            [self showAlertMessage:[NSString stringWithFormat:@"%@",theReply] withTitle:@"Alert!!!"];
        }
        else
        {
            [self createTableView];
            vimeoVideoTable.hidden=NO;
            [vimeoVideoTable reloadData];
            NSLog(@"got response== %@",response);
        }
    }
    else
    {
        NSLog(@"faield to connect");
    }
    
    
    if ([responseData length] == 0 && err == nil)
    {
        NSLog(@"Nothing was downloaded.");
    }
    else if (err != nil){
    
        if ([[err description] rangeOfString:@"The Internet connection appears to be offline"].location != NSNotFound)
        {
            NSLog(@"string does not contain ");
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert!!!" message:@"Please Check your Internet Connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        NSLog(@"Error = %@", err);
    }
    
    }
    
    -(void)createTableView
    {
    if (vimeoVideoTable !=nil)
    {
        [vimeoVideoTable removeFromSuperview];
        vimeoVideoTable=nil;
    }
    vimeoVideoTable=[[UITableView alloc]initWithFrame:CGRectMake(10, 20, 300, self.view.bounds.size.height-100)];
    [vimeoVideoTable setDelegate:self];
    [vimeoVideoTable setHidden:YES];
    [vimeoVideoTable setDataSource:self];
    [self.view addSubview:vimeoVideoTable];
    //[vimeoVideoTable reloadData];
    
    }
    

    【讨论】:

    【解决方案6】:

    使用这个

    NSMutableString *html = [[NSMutableString alloc] initWithCapacity:1] ;
    [html appendString:@"<html><head>"];
    [html appendString:@"<style type=\"text/css\">"];
    [html appendString:@"body {"];
    [html appendString:@"background-color: transparent;"];
    [html appendString:@"color: white;"];
    [html appendString:@"}"];
    [html appendString:@"</style>"];
    [html appendString:@"</head><body style=\"margin:0\">"];
    [html appendString:@"<iframe src=\"//player.vimeo.com/video/84403700?autoplay=1&amp;loop=1\" width=\"1024\" height=\"768\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"];
    [html appendString:@"</body></html>"];
    
    
    [viewWeb loadHTMLString:html baseURL:urlMovie];
    

    【讨论】:

    • 我收到消息“您当前的设置无法播放此视频”
    【解决方案7】:

    我绝对建议youtube_ios_player_helper,“赞助”Google

    import youtube_ios_player_helper
    
    class YTViewController: YTPlayerViewDelegate {
    
        @IBOutlet weak var player: YTPlayerView!
    
        // MARK: - Public properties -
    
        var videoID = "k_okcNVZqqI"
    
        // MARK: - View life cycle -
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.player.delegate = self
        }
    
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
            self.load()
            self.player.fadeOut()
        }
    
        /**
         Play video with the relative youtube identifier.
         */
        func load() {
            Utils.showHUD(self.view)
            let options = ["playsinline" : 1]
            self.player.loadWithVideoId(self.videoID, playerVars: options)
        }
    
        /**
         Stop video playing.
         */
        func stop() {
        }
    
        // MARK: - YOUTUBE video player delegate -
    
        func playerViewDidBecomeReady(playerView: YTPlayerView) {
            self.player.playVideo()
        }
    
        func playerView(playerView: YTPlayerView, didChangeToState state: YTPlayerState) {
            switch state {
            case .Playing:
                self.player.fadeIn(duration: 0.5)
                Utils.hideHUD(self.view)
                print("Started playback")
                break;
            case .Paused:
                print("Paused playback")
                break;
            default:
                break;
            }
        }
    }
    

    【讨论】:

      【解决方案8】:

      我使用以下方法成功解决了同样的问题。

      使用youtube-ios-player-helper并添加代码:

      [_playerView loadWithVideoId:@"DmTzboEqfNk" playerVars:@{
                                                               @"playsinline" : @1
                                                               }];
      

      您可以在Youtube > IFrame API 中找到更多变量。

      【讨论】:

        【解决方案9】:

        我在情节提要中使用了 WKWebView 并添加了代码:

        func playVideo() {
        
        if yourLink.lowercased().contains("youtu.be"){
            getVideo(videoCode: yourVideoCode)
            if let range = yourLink.range(of: "be/"){
                let videoId = yourLink[range.upperBound...].trimmingCharacters(in: .whitespaces)
                getVideo(videoCode: videoId)
            }
        } else if yourLink.lowercased().contains("youtube.com"){
            if let range = yourLink.range(of: "?v="){
                let videoId = yourLink[range.upperBound...].trimmingCharacters(in: .whitespaces)
                getVideo(videoCode: videoId)
            }
        } else if yourLink.lowercased().contains("vimeo.com") {
            let url: NSURL = NSURL(string: yourLink)
            webKitView.contentMode = UIViewContentMode.scaleAspectFit
            webKitView.load(URLRequest(url: url as URL))
        }
        }
        
        func getVideo(videoCode: String) {
            guard
            let url = URL(string: "https://www.youtube.com/embed/\(videoCode)")
            else { return }
            webKitView.load(URLRequest(url: url))
        }
        

        要从 youtube/Vimeo 链接获取 videoId,请参考:

        Youtube Video Id from URL - Swift3

        Regex to get vimeo video id in swift 2

        希望能有所帮助! :)

        【讨论】:

          猜你喜欢
          • 2011-04-25
          • 2011-11-16
          • 2012-04-05
          • 1970-01-01
          • 2012-11-05
          • 2011-08-27
          • 1970-01-01
          • 2018-08-06
          • 1970-01-01
          相关资源
          最近更新 更多