屏幕锁定时不显示播放器

时间:2019-03-26 11:25:40

标签: swift4 ios10 avaudioplayer

我无法在锁定屏幕(iOS 10 +)上显示播放器控件。

我在“背景模式”中检查“音频”:

enter image description here

设置音频会话:

import UIKit

import AVFoundation
import MediaPlayer

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var audio: AVAudioPlayer?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        let audioSession = AVAudioSession.sharedInstance()

        do {

            try audioSession.setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: [])
            try audioSession.setActive(true)

        } catch {
            print(error)
        }

        do {
            let url = Bundle.main.url(forResource: "example", withExtension: "mp3")
            audio = try AVAudioPlayer(contentsOf: url!)
        } catch {
            print(error)
        }

        audio?.play()

        var nowPlayingInfo = [String : Any]()
        nowPlayingInfo[MPMediaItemPropertyArtist] = "Artist"
        nowPlayingInfo[MPMediaItemPropertyTitle] = "My Track"

        if let image = UIImage(named: "image") {
            nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
                return image
            }
        }

        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = audio!.currentTime
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = audio!.duration
        nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = audio!.rate

        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo

        return true
    }

}

在屏幕被阻塞后,音频会继续播放,但此时锁定屏幕上没有播放器控件。

我的解决方案出了什么问题?

0 个答案:

没有答案