Xcode swift -背景模式-锁定时AVPlayer中的音频

b1payxdu  于 2023-01-21  发布在  Swift
关注(0)|答案(3)|浏览(151)

我有一个AVPlayer设置,但我似乎不能得到视频音频继续播放时,手机被锁定或在主屏幕上。我已经编辑了info.plist并启用了音频背景模式,但我认为需要添加一些代码。请你能帮我。谢谢
下面是我的代码:

import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

    @IBAction func WarmUp(sender: UIButton)
    {
        WarmUpVideo()
    }

    func WarmUpVideo()
    {
        let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "MOV")
        let videoURL = NSURL(fileURLWithPath: filePath!)

        let player = AVPlayer(URL: videoURL)
        let playerViewController = AVPlayerViewController()

        playerViewController.player = player

        self.presentViewController(playerViewController, animated: true) { () -> Void in playerViewController.player!.play()
        }

    }

    func playExternalVideo()
    {

}

    @IBAction func CoolDown(sender: UIButton)
    {
        CoolDownVideo()
    }

    func CoolDownVideo()
    {
        let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "mp4")
        let videoURL = NSURL(fileURLWithPath: filePath!)

        let player = AVPlayer(URL: videoURL)
        let playerViewController = AVPlayerViewController()

        playerViewController.player = player

        self.presentViewController(playerViewController, animated: true) { () -> Void in playerViewController.player!.play()
        }

    }

}
tpxzln5u

tpxzln5u1#

我认为您遗漏了以下代码:

do {
    try AVAudioSession.sharedInstance()
                          .setCategory(AVAudioSession.Category.playback)
    print("AVAudioSession Category Playback OK")
    do {
        try AVAudioSession.sharedInstance().setActive(true)
        print("AVAudioSession is Active")
    } catch let error as NSError {
        print(error.localizedDescription)
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

将其添加到viewDidLoad中。
关键代码行的典型2019语法:

try AVAudioSession.sharedInstance().setCategory(.playback)

在某些情况下,您可能需要:

try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)

你必须在plist中添加这个ONE项目(只能添加一个项目,小心老例子);

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>

即:

注:几年前,您还必须添加 UIApplicationExitsOnSuspend -不要今天添加此选项。

wz8daaqr

wz8daaqr2#

我在苹果的文档中找到了解决方案。除了背景模式,你需要将播放器设置为零以避免自动暂停。
以下是链接:
https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/creating_a_basic_video_player_ios_and_tvos/playing_audio_from_a_video_asset_in_the_background

yvt65v4c

yvt65v4c3#

对我有效的方法是将这些值添加到Info.plist中:

相关问题