ios iPhone SDK:如何在视图中播放视频?而不是全屏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1266750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:17:11  来源:igfitidea点击:

iPhone SDK:How do you play video inside a view? Rather than fullscreen

iosobjective-cmedia-playermpmovieplayer

提问by Sam

I am trying to play video inside a UIView, so my first step was to add a class for that view and start playing a movie in it using this code:

我正在尝试在 a 中播放视频UIView,所以我的第一步是为该视图添加一个类并使用以下代码开始在其中播放电影:

- (IBAction)movie:(id)sender{
    NSBundle *bundle = [NSBundle mainBundle];
        NSString *moviePath = [bundle pathForResource:@"Movie" ofType:@"m4v"];
    NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
    MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    theMovie.scalingMode = MPMovieScalingModeAspectFill;
    [theMovie play];
}

But this just crashes the app when using this method inside it's own class, but is fine elsewhere. Does anyone know how to play video inside a view? and avoid it being full screen?

但是,在它自己的类中使用此方法时,这只会使应用程序崩溃,但在其他地方很好。有谁知道如何在视图中播放视频?并避免全屏显示?

回答by tobyc

As of the 3.2 SDK you can access the view property of MPMoviePlayerController, modify its frame and add it to your view hierarchy.

从 3.2 SDK 开始,您可以访问 的视图属性MPMoviePlayerController,修改其框架并将其添加到您的视图层次结构中。

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
player.view.frame = CGRectMake(184, 200, 400, 300);
[self.view addSubview:player.view];
[player play];

There's an example here: http://www.devx.com/wireless/Article/44642/1954

这里有一个例子:http: //www.devx.com/wireless/Article/44642/1954

回答by mdziadkowiec

The best way is to use layers insted of views:

最好的方法是使用层插入视图:

AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; // 

AVPlayerLayer *layer = [AVPlayerLayer layer];

[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

[self.view.layer addSublayer:layer];

[player play];

Don't forget to add frameworks:

不要忘记添加框架:

#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"

回答by Suragch

Swift

迅速

This is a self contained project so that you can see everything in context.

这是一个自包含项目,因此您可以在上下文中查看所有内容。

Layout

布局

Create a layout like the following with a UIViewand a UIButton. The UIViewwill be the container in which we will play our video.

使用 aUIView和 a创建如下布局UIButton。该UIView会中,我们将发挥我们的视频容器。

enter image description here

在此处输入图片说明

Add a video to the project

向项目添加视频

If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answerfor more).

如果您需要一个示例视频来练习,您可以从sample-videos.com获取一个。我在这个例子中使用了 mp4 格式的视频。将视频文件拖放到您的项目中。我还必须将它显式添加到捆绑资源中(转到Build Phases > Copy Bundle Resources,更多信息请参见此答案)。

Code

代码

Here is the complete code for the project.

这是该项目的完整代码。

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVPlayer?

    @IBOutlet weak var videoViewContainer: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        initializeVideoPlayerWithVideo()
    }

    func initializeVideoPlayerWithVideo() {

        // get the path string for the video from assets
        let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
        guard let unwrappedVideoPath = videoString else {return}

        // convert the path string to a url
        let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)

        // initialize the video player with the url
        self.player = AVPlayer(url: videoUrl)

        // create a video layer for the player
        let layer: AVPlayerLayer = AVPlayerLayer(player: player)

        // make the layer the same size as the container view
        layer.frame = videoViewContainer.bounds

        // make the video fill the layer as much as possible while keeping its aspect size
        layer.videoGravity = AVLayerVideoGravity.resizeAspectFill

        // add the layer to the container view
        videoViewContainer.layer.addSublayer(layer)
    }

    @IBAction func playVideoButtonTapped(_ sender: UIButton) {
        // play the video if the player is initialized
        player?.play()
    }
}

Notes

笔记

  • If you are going to be switching in and out different videos, you can use AVPlayerItem.
  • If you are only using AVFoundationand AVPlayer, then you have to build all of your own controls. If you want full screen video playback, you can use AVPlayerViewController. You will need to import AVKitfor that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Hereand hereare some video tutorials.
  • MPMoviePlayerControllerthat you may have seen in other answers is deprecated.
  • 如果您要切换不同的视频,您可以使用AVPlayerItem.
  • 如果您只使用AVFoundationand AVPlayer,那么您必须构建自己的所有控件。如果你想全屏播放视频,你可以使用AVPlayerViewController. 您需要为此导入AVKit。它带有一整套用于暂停、快进、快退、停止等的控件。这里这里有一些视频教程。
  • MPMoviePlayerController您可能在其他答案中看到的内容已被弃用。

Result

结果

The project should look like this now.

该项目现在应该是这样的。

enter image description here

在此处输入图片说明

回答by jrc

Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.frameworkto your target.

查看您的代码,您需要设置电影播放器​​控制器视图的框架,并将电影播放器​​控制器的视图添加到您的视图中。另外,不要忘记将MediaPlayer.framework添加到您的目标。

Here's some sample code:

这是一些示例代码:

#import <MediaPlayer/MediaPlayer.h>

@interface ViewController () {
    MPMoviePlayerController *moviePlayerController;
}

@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Instantiate a movie player controller and add it to your view
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];    
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    [moviePlayerController.view setFrame:self.movieView.bounds];  // player's frame must match parent's
    [self.movieView addSubview:moviePlayerController.view];

    // Configure the movie player controller
    moviePlayerController.controlStyle = MPMovieControlStyleNone;        
    [moviePlayerController prepareToPlay];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Start the movie
    [moviePlayerController play];
}

@end

回答by Shailesh

NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];

[self presentMoviePlayerViewControllerAnimated:playerv];

回答by Darshan Kunjadiya

NSURL *url = [NSURL URLWithString:[exreciesDescription objectForKey:@"exercise_url"]];
moviePlayer =[[MPMoviePlayerController alloc] initWithContentURL: url];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doneButtonClicked) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
[[moviePlayer view] setFrame: [self.view bounds]];  // frame must match parent view
[self.view addSubview: [moviePlayer view]];
[moviePlayer play];

-(void)playMediaFinished:(NSNotification*)theNotification 
{
    moviePlayer=[theNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:moviePlayer];


    [moviePlayer.view removeFromSuperview];
}

-(void)doneButtonClicked
  {
         [moviePlayer stop];
        [moviePlayer.view removeFromSuperview];
         [self.navigationController popViewControllerAnimated:YES];//no need this if you are      opening the player in same screen;
  }

回答by Beninho85

Swift version:

迅捷版:

import AVFoundation

func playVideo(url: URL) {

    let player = AVPlayer(url: url)

    let layer: AVPlayerLayer = AVPlayerLayer(player: player)
    layer.backgroundColor = UIColor.white.cgColor
    layer.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    layer.videoGravity = .resizeAspectFill
    self.view.layer.addSublayer(layer)

    player.play()
}

回答by Chandramani

Use the following method.

使用以下方法。

self.imageView_VedioContaineris the container view of your AVPlayer.

self.imageView_VedioContainer是您的AVPlayer.

- (void)playMedia:(UITapGestureRecognizer *)tapGesture
{
    playerViewController = [[AVPlayerViewController alloc] init];

    playerViewController.player = [AVPlayer playerWithURL:[[NSBundle mainBundle]
                                                 URLForResource:@"VID"
                                                         withExtension:@"3gp"]];
    [playerViewController.player play];
    playerViewController.showsPlaybackControls =YES;
    playerViewController.view.frame=self.imageView_VedioContainer.bounds;
    [playerViewController.view setAutoresizingMask:UIViewAutoresizingNone];// you can comment this line 
    [self.imageView_VedioContainer addSubview: playerViewController.view];
}

回答by zpesk

You cannot play a video inside a view. It has to be played fullscreen.

您无法在视图内播放视频。它必须全屏播放。