使用Swift 3在后台运行应用程序时如何在iOS 10中播放声音

Off*_*Bad 2 avaudioplayer ios swift swift3 ios10

我正在开发一个运动应用程序,当该应用程序进入后台以及锁定屏幕时,它需要能够播放声音。我还需要允许播放其他应用程序的声音(例如音乐),同时还要使我的声音效果通过。

我通过使用AVAudioSessionCategoryAmbient在iOS 9中进行了此操作,但是一旦我的应用程序变为非活动状态或屏幕锁定,声音就会停止。

这是演示应用程序中我的代码的简化版本:

import UIKit
import AVFoundation

class ViewController: UIViewController {

var session: AVAudioSession = AVAudioSession.sharedInstance()
var timer = Timer()
let countdownSoundFile = "154953__keykrusher__microwave-beep"
let countdownSoundExt = "wav"
var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    activateAudio()

}

func activateAudio() {
        _ = try? session.setCategory(AVAudioSessionCategoryAmbient, with: [])
        _ = try? session.setActive(true, with: [])
}

@IBAction func play() {
    timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(ViewController.playSound), userInfo: nil, repeats: true)
}

func playSound() {

    if let soundURL = Bundle.main.url(forResource: countdownSoundFile, withExtension: countdownSoundExt) {
        do {

            print("sound playing")
            try audioPlayer = AVAudioPlayer(contentsOf: soundURL)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print("no sound found")
        }
    }

}
}
Run Code Online (Sandbox Code Playgroud)

我还检查了“ Audio, Airplay, and Picture in Picture后台模式”中的功能,这将“必需”后台模式添加到了我的plist中。

我正在设备上对此进行测试,一旦锁定屏幕或按下主屏幕按钮,我的声音就会停止,一旦我的应用再次激活,它们就会恢复。

我通过使用以下方法找到了解决方法:

var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound);
Run Code Online (Sandbox Code Playgroud)

但这不允许更改声音的音量,并且我还需要使用AVSpeechSynthesizer,并且此解决方法对此无效。

关于我可以做些什么的任何想法?

编辑:

我将类别行更改为_ = try? session.setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers]),这允许在应用程序运行时播放音乐,但是当屏幕锁定或进入背景时声音仍会停止。在这些情况下,我需要继续播放声音。

编辑:

如答案所指出,当我的应用程序处于后台时,我无法播放声音,但是使用时,_ = try? session.setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers])确实可以在屏幕关闭并与其他应用程序的声音(音乐)混合时播放声音。

mat*_*att 5

您不能在环境音频会话类别的背景下播放。您的类别必须是“播放”。

要允许其他应用程序播放声音,请使用可混合选项(.mixWithOthers)修改“播放”类别。

(还请记住,您可以随时更改类别。大多数情况下,您可以将其设置为“环境”,但是当您知道要进入后台时可以切换到“播放”,以便继续播放。)

编辑我也想到,还有另一种可能的误解可能需要解决。在后台时,您无法(轻松)开始新的声音。当应用程序进入后台时,背景音频只允许您继续播放当前声音。一旦声音停止(在后台),您的应用就会暂停,然后结束。

  • 并且还需要为音频启用“背景模式功能”。 (3认同)