【发布时间】:2016-11-17 03:21:04
【问题描述】:
我正在开发一个锻炼应用程序,该应用程序需要能够在应用程序进入后台以及屏幕锁定时播放声音。我还需要允许播放来自其他应用的声音(例如音乐),同时还允许播放我的音效。
我在 iOS 9 中使用 AVAudioSessionCategoryAmbient 进行了这项工作,但是一旦我的应用程序变为非活动状态或屏幕锁定,声音就会停止。
这是我在演示应用中的代码的简化版本:
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")
}
}
}
}
我还检查了后台模式中的Audio, Airplay, and Picture in Picture 功能,它在我的 plist 中添加了必需的后台模式。
我正在设备上对此进行测试,一旦我锁定屏幕或按下主页按钮,我的声音就会停止,一旦我的应用再次激活,声音就会恢复。
我找到了解决方法:
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound);
但是这不允许改变声音的音量,而且我还需要使用 AVSpeechSynthesizer,这个解决方法不起作用。
关于我可以做些什么来完成这项工作的任何想法?
编辑:
我将类别行更改为_ = try? session.setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers]),这允许在应用程序运行时播放音乐,但是当屏幕锁定或进入后台时声音仍然停止。我需要声音在这些场景中继续播放。
编辑:
正如答案所指出的,当我的应用程序处于后台时,我无法播放声音,但使用 _ = try? session.setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers]) 确实允许在屏幕关闭并与来自其他应用程序的声音(音乐)混合时播放声音。
【问题讨论】:
标签: ios swift swift3 avaudioplayer ios10