iOS:开始从后台播放声音

标签 ios background avfoundation avaudioplayer

我需要在用户关闭应用时开始播放声音。我使用 applicationDidEnterBackground 方法。在这里:

func applicationDidEnterBackground(application: UIApplication) {
    let dispatchQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    dispatch_async(dispatchQueue, {[weak self] in

        var audioSessionError: NSError?
        let audioSession = AVAudioSession.sharedInstance()
        NSNotificationCenter.defaultCenter().addObserver(self!,
            selector: "handleInterruption:",
            name: AVAudioSessionInterruptionNotification,
            object: nil)

        audioSession.setActive(true, error: nil)

        if audioSession.setCategory(AVAudioSessionCategoryPlayback,
            error: &audioSessionError){
                println("Successfully set the audio session")
        } else {
            println("Could not set the audio session")
        }

        let filePath = NSBundle.mainBundle().pathForResource("MySong",
            ofType:"mp3")

        let fileData = NSData(contentsOfFile: filePath!,
            options: .DataReadingMappedIfSafe,
            error: nil)

        var error:NSError?

        /* Start the audio player */
        self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error)

        /* Did we get an instance of AVAudioPlayer? */
        if let theAudioPlayer = self!.audioPlayer{
            theAudioPlayer.delegate = self;
            if theAudioPlayer.prepareToPlay() &&
                theAudioPlayer.play(){
                    println("Successfully started playing")
            } else {
                println("Failed to play")
            }
        } else {
            /* Handle the failure of instantiating the audio player */
        }
        })

}
func handleInterruption(notification: NSNotification){
/* Audio Session is interrupted. The player will be paused here */

let interruptionTypeAsObject =
notification.userInfo![AVAudioSessionInterruptionTypeKey] as! NSNumber

let interruptionType = AVAudioSessionInterruptionType(rawValue:
  interruptionTypeAsObject.unsignedLongValue)

if let type = interruptionType{
  if type == .Ended{

    /* resume the audio if needed */

  }
}

}

func audioPlayerDidFinishPlaying(播放器: AVAudioPlayer!, 成功标记:Bool){

  println("Finished playing the song")

  /* The flag parameter tells us if the playback was successfully
  finished or not */
  if player == audioPlayer{
    audioPlayer = nil
  }
  }

它不起作用。调试后我看到 theAudioPlayer.play() 返回 false。例如,如果我在 applicationDidFinishLaunching 中运行此代码,它会播放声音。我将后台模式 App plays audio or streams audio/video using AirPlay 添加到我的 Info.plist 这里有什么问题?

最佳答案

在最基本的层面上,您的应用应满足三个先决条件才能在后台播放音频:

  • 必须正在播放音乐
  • 在目标功能中为音频设置“背景模式”。

  • 对于基本播放,初始化您的 Audio Session ,并将您的 Audio Session 类别设置为 AVAudioSessionCategoryPlayback。如果不这样做,您将获得默认行为。

您还应该配置您的应用以响应

  • 音频输出的变化
  • Audio Session 中断(例如电话)
  • 远程控制事件(通过控制中心或锁定屏幕)

查看 this Swift 示例。

关于iOS:开始从后台播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31102299/

相关文章:

ios - 创建 p2p 连接 iOS

css - 溢出 :hidden not working

Swift - 后台蓝牙写入特性

android - 如何以编程方式在自定义标题栏上设置背景颜色渐变?

iphone - 在文件名中使用斜杠保存文件 - objective-c

ios - QuickTime Player 是否需要通过 iTunes 安装 iOS 应用程序?

ios - 什么是 "Scanning for working copies"

iphone - 在 iOS 中同时录制和播放音频

ios - 获取音频队列缓冲区的 <AudioTimeStamp>

ios - 锁定设备时记录音频