iPhone SDK :보기 내에서 비디오를 어떻게 재생합니까? 전체 화면보다는
-
13-09-2019 - |
문제
나는 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];
}
그러나 이것은 자체 클래스 내 에서이 방법을 사용할 때 앱이 충돌하지만 다른 곳에서는 괜찮습니다. 뷰 안에서 비디오를 재생하는 방법을 아는 사람이 있습니까? 그리고 전체 화면이 아닌지?
해결책
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];
여기에는 예가 있습니다. http://www.devx.com/wireless/article/44642/1954
다른 팁
가장 좋은 방법은 뷰가 등장하는 레이어를 사용하는 것입니다.
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];
프레임 워크를 추가하는 것을 잊지 마십시오 :
#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"
코드를 살펴보면 영화 플레이어 컨트롤러보기의 프레임을 설정하고 영화 플레이어 컨트롤러의보기를보기에 추가해야합니다. 또한 추가하는 것을 잊지 마십시오 MediaPlayer.Framework 당신의 목표에.
샘플 코드는 다음과 같습니다.
#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
빠른
이것은 자체적으로 포함 된 프로젝트로, 모든 것을 맥락에서 볼 수 있습니다.
형세
다음과 같은 레이아웃을 만듭니다 UIView
그리고 a UIButton
. 그만큼 UIView
비디오를 재생할 컨테이너가 될 것입니다.
프로젝트에 비디오를 추가하십시오
연습 할 샘플 비디오가 필요한 경우 샘플-videos.com. 이 예에서는 MP4 형식 비디오를 사용하고 있습니다. 비디오 파일을 프로젝트로 드래그 앤 삭제하십시오. 또한 번들 자원에 명시 적으로 추가해야했습니다 ( 위상> 복사 번들 리소스를 구축하십시오, 보다 이 답변 이상).
암호
프로젝트의 전체 코드는 다음과 같습니다.
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()
}
}
메모
- 다른 비디오를 전환하거나 나가려면 사용할 수 있습니다.
AVPlayerItem
. - 만 사용하는 경우
AVFoundation
그리고AVPlayer
, 그런 다음 자신의 컨트롤을 모두 구축해야합니다. 전체 화면 비디오 재생을 원한다면 사용할 수 있습니다.AVPlayerViewController
. 가져와야합니다AVKit
그에 대한. 일시 정지, 빠른 전진, 되감기, 정지 등을위한 전체 컨트롤 세트가 제공됩니다. 여기 그리고 여기 일부 비디오 자습서입니다. MPMoviePlayerController
다른 답변에서 보았을 수도 있다는 것은 더 이상 사용되지 않습니다.
결과
프로젝트는 지금 이렇게 보일 것입니다.
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;
}
스위프트 버전 :
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()
}
다음 방법을 사용하십시오.
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];
}
뷰 안에서 비디오를 재생할 수 없습니다. 전체 화면을 연주해야합니다.