【问题标题】:How Do I Get Audio Controls on Lock Screen/Control Center from AVAudioPlayer in Swift如何从 Swift 中的 AVAudioPlayer 获取锁定屏幕/控制中心的音频控件
【发布时间】:2016-04-13 18:57:41
【问题描述】:

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

我对@9​​87654323@ 和MPNowPlayingInfoCenter 的使用只是阅读其他相关帖子的实验。

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

【问题讨论】:

  • 有什么问题/问题?
  • 问题是我如何获得锁定屏幕的音频控制。我已经看到 MPNowPlayingInfoCenter nowPlayingInfo 是将歌曲元数据传递到锁定屏幕/控制中心的方式,但我缺少如何将其与 AVAudioPlayer 联系起来
  • 锁屏界面已经有音频控制了。
  • 没有为我的应用播放音频显示控件
  • 但是,我需要将后台模式设置为“应用程序播放音频或流式传输音频......”。有趣的是,在 xcode 中使用模拟器时,音频会在后台播放,但是当我将应用程序部署到实际设备时,它就不起作用了。后台模式配置中可能缺少某些内容,但除了将该属性添加到 info.plist 之外,我似乎找不到任何东西

标签: ios swift avfoundation avaudioplayer mpmusicplayercontroller


【解决方案1】:

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

斯威夫特 3.1

UIApplication.shared.beginReceivingRemoteControlEvents()

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

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

【讨论】:

  • 最终答案,UIApplication.sharedApplication().beginReceivingRemoteControlEvents()AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
  • 这些行应该放在哪里?尽管音频播放正常,但我无法为我的应用显示任何锁定屏幕控件
  • @mike 在 appdelege 的 didFinishLaunchOptions 中。它晚了,但这个链接很有用developer.apple.com/library/content/samplecode/…
  • 根据@commando24提供的示例代码中的自述文件,“使用MPRemoteCommandCenter时不需要调用UIApplication.beginReceivingRemoteControlEvents()。”
  • 在 iOS 7.1 及更高版本中,使用共享的 MPRemoteCommandCenter 对象注册远程控制事件。使用共享命令中心对象时不需要调用beginReceivingRemoteControlEvents 方法。
【解决方案2】:

要实现此功能,请将媒体播放器框架的 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
}

更多信息请咨询苹果官方Documentation

【讨论】:

  • 我可以在模拟器中看到这个吗?
  • 模拟器在锁屏界面没有音频控制选项!
【解决方案3】:
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{}
}

【讨论】:

  • + 代表mpic.nowPlayingInfo
【解决方案4】:

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

【讨论】:

  • 我在书中解释了一种方法;此处的示例代码:github.com/mattneub/Programming-iOS-Book-Examples/blob/master/… 或者您可以使用 MPRemoteCommandCenter。
  • 哈哈,好吧。其实我之前也在看这个。我将探索它的远程控制端。关于为什么后台模式可能在模拟器中工作但在实际 iPhone 上不起作用的任何想法
  • 模拟器在后台模式方面是不可靠的——不要将它用于这方面的任何类型的实验。这是一个已知的、公认的错误。
  • 不幸的是上面的链接坏了
【解决方案5】:

我有这个问题。你只需要

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

【讨论】:

  • 这是为我整理的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多