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

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

我有一个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()
        }

    }

}
ios xcode audio avplayer
2个回答
6
投票

我想你错过了以下代码:

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    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。


0
投票

我在Apple的文档中找到了解决方案。除了背景模式,您需要将播放器设置为nil以避免自动暂停。

这是链接:

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

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