ios - Xcode swift - 后台模式 - 锁定时 AVPlayer 中的音频

标签 ios xcode audio avplayer

我已经设置了 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()
        }

    }

}

最佳答案

我认为您缺少以下代码:

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 中添加此一个项(仅限一项,请注意旧示例);

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

这是:

enter image description here

注意:几年前您还必须添加UIApplicationExitsOnSuspend - 今天不要添加它。

关于ios - Xcode swift - 后台模式 - 锁定时 AVPlayer 中的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37766625/

相关文章:

objective-c - UIScrollView 不会在设备上滚动

iOS (cs193p) : Why are my UISplitViewControllerDelegate delegate methods not called on orientation change?

objective-c - 将时间戳添加到 Objective C URL 另存为?

ios - 带有 UIImage 的 UITableViewCell,宽度不会在初始显示的单元格上更新

Windows shell : How can I get the audio device(s) name(s)?

Python sounddevice 模块输出 Traceback (最近一次调用最后一次) :

delphi - 仅提供音频的 DirectShow 推送源过滤器的正确样本大小是多少?

iOS 应用程序通过 USB 电缆连接与在 OSX 中运行的应用程序通信

ios - 如何添加具有特定边界的空白 UIImageView 作为 UIStackView 的子级?

ios - 如何在后面创建带有水印 UIImageView 的 UIView?