如何从Swift中的AVAudioPlayer获取锁定屏幕/控制中心的音频控件

nbp*_*eth 17 avfoundation avaudioplayer mpmusicplayercontroller ios 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{}
}
Run Code Online (Sandbox Code Playgroud)

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

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

Leo*_*bus 27

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

Swift 3.1

UIApplication.shared.beginReceivingRemoteControlEvents()
Run Code Online (Sandbox Code Playgroud)

如果要为MPRemoteCommandCenter指定自定义操作:

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))
Run Code Online (Sandbox Code Playgroud)

  • 最后的答案,`UIApplication.sharedApplication().beginReceivingRemoteControlEvents()`和`AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)` (4认同)
  • 这些线应该放在哪里?尽管音频播放正常,但我无法为我的应用显示任何锁定屏幕控件 (2认同)
  • 在 iOS 7.1 及更高版本中,使用共享的 MPRemoteCommandCenter 对象注册远程控制事件。使用共享命令中心对象时,不需要调用`beginReceivingRemoteControlEvents`方法。 (2认同)

Sre*_*tan 15

要实现此功能,请将媒体播放器框架的MPRemoteCommandCenterMPNowPlayingInfoCenter类与AVPlayer 一起使用

import MediaPlayer
import AVFoundation

// Configure AVPlayer
var player = AVPlayer()
Run Code Online (Sandbox Code Playgroud)

配置远程命令处理程序

以 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
    }
}
Run Code Online (Sandbox Code Playgroud)

提供显示元数据

使用 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
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅 Apples 官方文档

  • 模拟器在锁定屏幕中没有音频控制选项。! (3认同)