在 Swift/Objective-C 中嵌入另一个视图控制器的视图中的 AVPlayerViewController 控件未显示

问题描述 投票:0回答:1

我正在尝试在 IOS 应用程序中通过简单的播放/暂停/停止功能来播放音频,而无需启动单独的 avPlayerViewController。

根据这个问题的答案,如果不使用Apple的AVPlayerViewController,就无法获得预制控件。但是,Apple 建议的解决方法是将 AVPlayerViewController 嵌入到另一个视图控制器的视图中。

我正在尝试执行此操作并且媒体正在播放,但是控件未显示。

这是我用 Objective-C 和 Swift 编写的代码。都无法上班。

目标-C

#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h>
/*in header file:
@property (nonatomic, strong) IBOutlet AVPlayerViewController *pVC;
*/
NSString* audiosurl = @"https://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Sevish_-__nbsp_.mp3";
NSURL * audioURL = [NSURL URLWithString:audiosurl];
  self.pVC = [AVPlayerViewController new];
  self.pVC.view.bounds= self.videoView.bounds;
  AVPlayer *avplayer = [AVPlayer playerWithURL:audioURL];
  // AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:avplayer];
  // playerLayer.frame = self.videoView.bounds;
  // [self.videoView.layer addSublayer:playerLayer];
   self.pVC.player = avplayer;
   self.pVC.showsPlaybackControls = YES;
   self.pVC.videoGravity = AVLayerVideoGravityResizeAspectFill;
   self.pVC.view.backgroundColor = [UIColor clearColor];
   [self.videoView addSubview:self.pVC.view];
   [avplayer play];

斯威夫特:

let videoURL = URL(string: "https://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Sevish_-__nbsp_.mp3")
let player = AVPlayer(url: videoUrl)
let playerViewController: AVPlayerViewController!
 playerViewController = AVPlayerViewController()
 playerViewController.view.frame = YOUR_FRAME_OR_EMBED_IN_STORYBOARD
 playerViewController.player = player
 playerViewController.showsPlaybackControls = true
 playerViewController.videoGravity = .resizeAspectFill
self.videoView.addSubview(playerViewController.view)
playerViewController.player!.play() 

想知道问题是否可能是背景颜色、视图层次结构的顺序、是否应该使用图层或其他东西。

是什么导致控件不可见?

感谢您的建议!

ios swift avfoundation avplayer avplayerviewcontroller
1个回答
0
投票

你所做的一切都是错误的。这不是将一个视图控制器的视图嵌入另一个视图控制器的方式。 如果您不知道如何嵌入,您可能会更喜欢

presented

视图控制器: self.present(playerViewController, animated: true)

只是为了向您展示如何嵌入,这里重写了您的代码,其中我们占据了整个父视图控制器的视图。请注意为了嵌入而必须执行的“舞蹈”:

let videoURL = URL(string: "https://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Sevish_-__nbsp_.mp3") let player = AVPlayer(url: videoURL!) let playerViewController = AVPlayerViewController() playerViewController.player = player self.addChild(playerViewController) self.view.addSubview(playerViewController.view) playerViewController.view.frame = self.view.bounds playerViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] playerViewController.didMove(toParent: self) playerViewController.player?.play()

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.