如何从 Swift 中的 AVAudioPlayer 获取锁定 Screen/Control 中心的音频控件

How Do I Get Audio Controls on Lock Screen/Control Center from AVAudioPlayer in Swift

iOS 开发的新手,所以开始吧。我有一个正在播放音频的应用程序 - 我正在使用 AVAudioPlayer 在应用程序的资产中按名称加载单个文件。我不想查询用户的图书馆,只查询提供的文件。效果很好,但是,我希望用户能够在锁定屏幕上暂停和调整音量。

func initAudioPlayer(file:String, type:String){
    let path = NSBundle.mainBundle().pathForResource(file, ofType: type)!
    let url = NSURL(fileURLWithPath: path)
    let audioShouldPlay = audioPlaying()
    do{
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        let audioPlayer:AVAudioPlayer = try AVAudioPlayer(contentsOfURL: url)
        audioPlayer.volume = slider.value
        audioPlayer.numberOfLoops = -1
        audioPlayer.prepareToPlay()
        if(audioShouldPlay){
            audioPlayer.play()
//                let mpic = MPNowPlayingInfoCenter.defaultCenter()
//                mpic.nowPlayingInfo = [MPMediaItemPropertyTitle:"title", MPMediaItemPropertyArtist:"artist"]
        }
    }
    catch{}
}

我对 AVAudioSessionMPNowPlayingInfoCenter 的使用只是阅读其他相关帖子的实验。

在我的应用程序的 plist 文件中为音频启用了后台模式

锁定屏幕("remote control"界面)上已经有音频控件。如果您想让他们控制您应用的音频,您需要将您的应用设为 远程控制目标 ,如 Apple's documentation.

中所述

您需要调用 beginReceivingRemoteControlEvents() 否则它将无法在实际设备上运行。

Swift 3.1

UIApplication.shared.beginReceivingRemoteControlEvents()

如果您想为 MPRemoteCommandCenter 指定自定义操作:

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))
func myplayer(file:String, type:String){
let path = NSBundle.mainBundle().pathForResource(file, ofType: type)!
let url = NSURL(fileURLWithPath: path)
let audioShouldPlay = audioPlaying()
do{
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)
    let audioPlayer:AVAudioPlayer = try AVAudioPlayer(contentsOfURL: url)
    audioPlayer.volume = slider.value
    audioPlayer.numberOfLoops = -1
    audioPlayer.prepareToPlay()
    if(audioShouldPlay){
        audioPlayer.play()
//                let mpic = MPNowPlayingInfoCenter.defaultCenter()
//                mpic.nowPlayingInfo = [MPMediaItemPropertyTitle:"title", 
MPMediaItemPropertyArtist:"artist"]
        }
    }
    catch{}
}

我有这个问题。你只需要

audioSession.setCategory(.playback, mode: .default) or 
audioSession.setCategory(.playback, mode: .default, options: 
                                               .init(rawValue: 0)) 

要实现此功能,请使用媒体播放器框架的 MPRemoteCommandCenter and MPNowPlayingInfoCenter classes with AVPlayer

import MediaPlayer
import AVFoundation

// Configure AVPlayer
var player = AVPlayer()

配置远程命令处理程序

以 MPRemoteCommand 对象的形式定义各种命令,您可以将自定义事件处理程序附加到这些对象以控制应用中的播放。

    func setupRemoteTransportControls() {
    // Get the shared MPRemoteCommandCenter
    let commandCenter = MPRemoteCommandCenter.shared()

    // Add handler for Play Command
    commandCenter.playCommand.addTarget { [unowned self] event in
        if self.player.rate == 0.0 {
            self.player.play()
            return .success
        }
        return .commandFailed
    }

    // Add handler for Pause Command
    commandCenter.pauseCommand.addTarget { [unowned self] event in
        if self.player.rate == 1.0 {
            self.player.pause()
            return .success
        }
        return .commandFailed
    }
}

提供显示元数据

使用 MPMediaItem 和 MPNowPlayingInfoCenter 定义的键提供元数据字典,并在 MPNowPlayingInfoCenter 的默认实例上设置该字典。

func setupNowPlaying() {
    // Define Now Playing Info
    var nowPlayingInfo = [String : Any]()
    nowPlayingInfo[MPMediaItemPropertyTitle] = "My Movie"

    if let image = UIImage(named: "lockscreen") {
        nowPlayingInfo[MPMediaItemPropertyArtwork] =
            MPMediaItemArtwork(boundsSize: image.size) { size in
                return image
        }
    }
    nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds
    nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds
    nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate

    // Set the metadata
    MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}

有关更多信息,请参阅苹果官方 Documentation