iPhone SDK: ¿Cómo se juega de vídeo dentro de un punto de vista? En lugar de pantalla completa

StackOverflow https://stackoverflow.com/questions/1266750

Pregunta

Estoy tratando de reproducir vídeo dentro de un UIView, así que mi primer paso fue añadir una clase para ese punto de vista y empezar a reproducir una película en la que el uso de este código:

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

Pero esto sólo se bloquea la aplicación cuando se utiliza este método dentro de su propia clase, pero está muy bien en otros lugares. ¿Alguien sabe cómo jugar de vídeo dentro de un punto de vista? y evite que el equipo de pantalla completa?

¿Fue útil?

Solución

A partir de la 3.2 SDK se puede acceder a la ventana de propiedades de MPMoviePlayerController, modificar su marco y añadirlo a su jerarquía de vistas.

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

Hay un ejemplo aquí: http://www.devx.com/wireless/Article / 44642/1954

Otros consejos

La mejor manera es usar capas insted de vista:

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

No se olvide de añadir marcos:

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

En cuanto a su código, es necesario establecer el marco de vista del controlador de reproductor de películas, y también añadir la vista del controlador reproductor de películas a la vista. Además, no se olvide de añadir MediaPlayer.framework a su objetivo.

A continuación, algunos ejemplos de código:

#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

Swift

Este es un proyecto independiente para que pueda ver todo en contexto.

Layout

Crear un diseño como el siguiente con un UIView y una UIButton. El UIView será el contenedor en el que vamos a jugar nuestro video.

 introducir descripci&oacute;n de la imagen aqu&iacute;

Añadir un vídeo al proyecto

Si necesita una muestra de vídeo para practicar, usted puede conseguir uno de sample-videos.com . Estoy usando un video en formato mp4 en este ejemplo. Arrastrar y soltar el archivo de vídeo en su proyecto. También he tenido que añadir explícitamente en los recursos de haces (ir a Crecimiento Fases> Copiar Bundle Recursos , ver este responder para más).

Código

Aquí está el código completo para el proyecto.

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()
    }
}

Notas

  • Si usted va a ser la conmutación de entrada y salida diferentes vídeos, puede utilizar AVPlayerItem .
  • Si sólo está utilizando AVFoundation y AVPlayer , entonces usted tiene que construir todos sus propios controles. Si desea que la reproducción de vídeo a pantalla completa, puede utilizar AVPlayerViewController . Tendrá que importar AVKit para eso. Viene con un conjunto completo de controles de pausa, avance rápido, rebobinado, parada, etc. Aquí y href="https://www.youtube.com/watch?v=WlLWLGeGfT8" aquí son algunos tutoriales en vídeo.
  • MPMoviePlayerController que puede haber visto en otras respuestas está en desuso.

Resultado

El proyecto debe tener este aspecto ahora.

 introducir descripci&oacute;n de la imagen aqu&iacute;

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

[self presentMoviePlayerViewControllerAnimated:playerv];
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;
  }

versión Swift:

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()
}

Utilice el método siguiente.

self.imageView_VedioContainer es la vista envase de su 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];
}

No se puede reproducir un vídeo dentro de una vista. Tiene que ser jugado pantalla completa.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top