2009-08-12 34 views
57

Tôi cố gắng để chơi video trong một UIView, vì vậy bước đầu tiên của tôi là để thêm một lớp để xem đó và bắt đầu chơi một bộ phim trong đó sử dụng mã này:iPhone SDK: Bạn phát video như thế nào bên trong chế độ xem? Thay vì fullscreen

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

Nhưng điều này chỉ treo các ứng dụng khi sử dụng phương thức này bên trong lớp riêng của nó, nhưng vẫn ổn ở nơi khác. Có ai biết cách chơi video trong một khung nhìn không? và tránh nó toàn màn hình?

Trả lời

83

Kể từ 3.2 SDK, bạn có thể truy cập thuộc tính chế độ xem của MPMoviePlayerController, sửa đổi khung của nó và thêm nó vào phân cấp chế độ xem của bạn.

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

Có một ví dụ ở đây: http://www.devx.com/wireless/Article/44642/1954

+0

Không hoạt động đối với các video trên youtube. Xem triển khai tại đây: http://iosdevelopertips.com/video/display-youtube-videos-without-exiting-your-application.html – cyrilchampier

+1

MPMoviePlayerController là thư viện xấu nếu bạn muốn kiểm soát cụ thể trong thời gian hiện tại trong video. Không chính xác, và có lỗi. Cách tốt nhất là AVPlayer, sử dụng AVPlayerLayer. – jose920405

-5

Bạn không thể phát video bên trong chế độ xem. Nó phải được phát toàn màn hình.

+0

Ok, cũng đó là một sự xấu hổ, nhưng tôi đã thấy các ứng dụng khác trên appstore nơi video đã được đóng không đầy đủ màn hình nhưng trong một cái nhìn nhỏ bên trong màn hình chính, vì vậy phải có một cách. – Sam

+4

Có thể những ví dụ về video-in-a-view đó là các hình ảnh liên tiếp với một âm thanh phụ. – mga

+0

Có thể là như vậy. Thật đáng buồn. – Sneakyness

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

[self presentMoviePlayerViewControllerAnimated:playerv]; 
+0

câu trả lời này là sai –

2
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; 
    } 
15

Nhìn vào mã của bạn , bạn cần đặt khung của v bộ điều khiển của trình phát phim và cũng có thể thêm chế độ xem của trình điều khiển trình phát phim vào chế độ xem của bạn. Ngoài ra, đừng quên thêm MediaPlayer.framework vào mục tiêu của bạn.

Dưới đây là một số mẫu mã:

#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 
+2

Tôi yêu bạn !! Cảm ơn bạn rất nhiều, tôi đã tìm kiếm ít nhất một giờ và bạn đã có mã duy nhất chỉ đơn giản là làm việc! – LinusGeffarth

+1

Xcode 6, iOS 8 và điều này vẫn hoạt động. Chìa khóa cho tôi là "chuẩn bị để chơi" ngoài câu trả lời khác. Cảm ơn! –

+0

cũng lưu ý rằng [moviePlayerController play]; là trong viewDidAppear ... nếu đây là trong viewDidLoad, bạn có thể chỉ thấy một nền đen trong "movieView" của bạn tùy thuộc vào phiên bản Xcode/iOS của bạn. – whyoz

33

Cách tốt nhất là sử dụng lớp insted quan điểm:

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

Đừng quên để thêm khung:

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

queuePlayer là gì? –

+2

Tôi đã thay đổi tên biến. – mdziadkowiec

+1

Tôi đã thực hiện việc này và tất cả những gì tôi nhận được là một hộp màu đỏ với âm thanh phát nhưng không có video:/ –

0

Sử dụng phương pháp sau đây.

self.imageView_VedioContainer là chế độ xem vùng chứa của 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]; 
} 
1

Swift phiên bản:

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

Sự khác biệt giữa nhập 'AVFoundation' so với 'AVKit' là gì? – Suragch

+0

Bạn không thêm một lớp khác vào mỗi lần người dùng phát video? – Suragch

+0

@Suragch Tôi không chắc chắn 100% nhưng tôi nghĩ AVKit được xây dựng dựa trên AVFoundation, một bộ Kit cũ hơn và cấp thấp hơn để quản lý Camera. Và có nó chỉ là một ví dụ vì vậy nó thêm một lớp mỗi lần nhưng nếu bạn có một số video để chơi chỉ cần chỉnh sửa các cầu thủ thay vì toàn bộ lớp – Beninho85

1

Swift

Đây là một dự án khép kín để bạn có thể nhìn thấy tất cả mọi thứ trong ngữ cảnh.

Layout

Tạo một bố cục như sau với một UIViewUIButton. UIView sẽ là vùng chứa trong đó chúng tôi sẽ phát video của mình.

enter image description here

Thêm video vào dự án

Nếu bạn cần một đoạn video mẫu để thực hành với, bạn có thể nhận được một từ sample-videos.com. Tôi đang sử dụng một video định dạng mp4 trong ví dụ này. Kéo và thả tệp video vào dự án của bạn. Tôi cũng phải thêm nó một cách rõ ràng vào tài nguyên bó (chuyển đến Tạo giai đoạn> Sao chép tài nguyên gói, xem this answer để biết thêm).

Đây là mã hoàn chỉnh cho dự án.

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

Ghi chú

  • Nếu bạn đang đi để được chuyển vào và ra khỏi video khác nhau, bạn có thể sử dụng AVPlayerItem.
  • Nếu bạn chỉ sử dụng AVFoundationAVPlayer, thì bạn phải xây dựng tất cả các điều khiển của riêng mình. Nếu bạn muốn phát lại video toàn màn hình, bạn có thể sử dụng AVPlayerViewController. Bạn sẽ cần phải nhập AVKit cho điều đó. Nó đi kèm với bộ điều khiển đầy đủ để tạm dừng, tua đi, tua lại, dừng, v.v. Herehere là một số hướng dẫn bằng video.
  • MPMoviePlayerController mà bạn có thể đã thấy trong các câu trả lời khác sẽ không được chấp nhận.

quả

Dự án sẽ trông như thế này ngay bây giờ.

enter image description here

Các vấn đề liên quan