概要
ios14からpicture in pictureがバックグラウンドでも再生できるということで試してみたんですがバックグラウンドに回したときに再生されません。どうしたら良いのでしょうか?
こちらのドキュメントを参考に試していました。
Adopting Picture in Picture in a Custom Player
コード
swift
1import UIKit 2import AVFoundation 3import AVKit 4 5class PlayerView: UIView { 6 override class var layerClass: AnyClass { 7 return AVPlayerLayer.self 8 } 9 var playerLayer: AVPlayerLayer! { 10 return layer as? AVPlayerLayer 11 } 12} 13 14class ViewController: UIViewController { 15 @IBOutlet weak var playButton: UIButton! 16 17 var playerController = AVPlayerViewController() 18 var player = AVPlayer() 19 var pictureInPictureController: AVPictureInPictureController! 20 let playerView = PlayerView() 21 22 override func viewDidLoad() { 23 super.viewDidLoad() 24 25 let startImage = AVPictureInPictureController.pictureInPictureButtonStartImage 26 let stopImage = AVPictureInPictureController.pictureInPictureButtonStopImage 27 28 playButton.setImage(startImage, for: .normal) 29 playButton.setImage(stopImage, for: .selected) 30 31 setupPictureInPicture() 32 } 33 34 func setupPictureInPicture() { 35 if AVPictureInPictureController.isPictureInPictureSupported() { 36 try!AVAudioSession.sharedInstance().setActive(true) 37 38 playerView.playerLayer.player = player 39 pictureInPictureController = AVPictureInPictureController(playerLayer: playerView.playerLayer) 40 41 } else { 42 fatalError("device not support") 43 } 44 } 45 46 47 @IBAction func playButtonTappedAction(_ sender: Any) { 48 guard let url = Bundle.main.url(forResource: "sample", withExtension: "mp4") else { 49 return 50 } 51 let item = AVPlayerItem(url: url) 52 player.replaceCurrentItem(with: item) 53 playerController.player = player 54 self.present(playerController, animated: true) { 55 self.player.play() 56 } 57 } 58} 59
あなたの回答
tips
プレビュー