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

时间:2016-01-09 00:05:23

标签: ios swift avfoundation avaudioplayer mpmusicplayercontroller

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文件中的音频启用了背景模式

5 个答案:

答案 0 :(得分:25)

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

Swift 3.1

UIApplication.shared.beginReceivingRemoteControlEvents()

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

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))

答案 1 :(得分:4)

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{}
}

答案 2 :(得分:3)

要实现此功能,请将Media Player框架的MPRemoteCommandCenterMPNowPlayingInfoCenter类与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
}

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

答案 3 :(得分:2)

锁定屏幕上已有音频控件(“遥控器”界面)。如果您希望他们控制您应用的音频,则需要将您的应用设为远程控制目标,如Apple's documentation中所述。

答案 4 :(得分:1)

我有这个问题。您只需要

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