当应用程序位于Swift 3的后台时,如何在iOS 10中播放声音
我正在开发一款运动应用程序,它需要能够在应用程序进入后台和屏幕锁定时播放声音。我还需要允许播放来自其他应用程序的声音(如音乐),同时也允许播放我的声音效果 我使用AVAudioSessionCategoryAmbient在iOS 9中实现了这一点,但一旦我的应用程序变为非活动状态或屏幕锁定,声音就会停止 以下是演示应用程序中我的代码的简化版本:当应用程序位于Swift 3的后台时,如何在iOS 10中播放声音,ios,swift,swift3,avaudioplayer,ios10,Ios,Swift,Swift3,Avaudioplayer,Ios10,我正在开发一款运动应用程序,它需要能够在应用程序进入后台和屏幕锁定时播放声音。我还需要允许播放来自其他应用程序的声音(如音乐),同时也允许播放我的声音效果 我使用AVAudioSessionCategoryAmbient在iOS 9中实现了这一点,但一旦我的应用程序变为非活动状态或屏幕锁定,声音就会停止 以下是演示应用程序中我的代码的简化版本: import UIKit import AVFoundation class ViewController: UIViewController {
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")
}
}
}
}
我还检查了背景模式下的音频、播放和画中画功能,这为我的plist添加了所需的背景模式
我正在一台设备上测试,一旦我锁定屏幕或按下home(主页)按钮,我的声音就会停止,一旦我的应用程序再次激活,声音就会恢复
我使用以下方法找到了解决方法:
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound);
但是这不允许改变声音的音量,我还需要使用AVSpeechSynthesizer,这个解决方法不适用于这个
我能做些什么来让这一切顺利进行,你有什么想法吗
编辑:
我将类别行更改为\uuux=try?session.setCategory(AVAudioSessionCategoryPlayback,with:[.mixWithOthers])
这允许在应用程序运行时播放音乐,但当屏幕锁定或进入后台时声音仍会停止。我需要声音在这些场景中继续播放
编辑:
正如答案所指出的,当我的应用程序在后台运行时,我不能播放声音,但使用\uux=try?session.setCategory(AVAudioSessionCategoryPlayback,with:[.mixWithOthers])
允许在屏幕关闭时播放声音,并与其他应用程序的声音(音乐)混合。您不能在背景下播放环境音频会话类别。您的类别必须为“播放”
要允许播放来自其他应用程序的声音,请使用Mixable选项(.mixWithOthers
)修改播放类别
(还请记住,您可以随时更改类别。您可以让它在大部分时间处于环境中,但当您知道要进入背景时,可以切换到播放,以便继续播放。)
编辑我还想到,还有一个可能的误解需要澄清。你不能(轻松地)在背景中发出新的声音。所有的背景音频允许你做的是继续播放当前的声音,当你的应用程序进入背景。一旦声音停止(在后台),你的应用程序就会暂停,到此结束。详细检查此处。您还需要从应用程序设置中启用音频模式
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch {
print(error)
}
} catch {
print(error)
}
还需要为音频启用后台模式功能。@iphone请阅读问题。他说是他干的。问题是为什么这还不够。@matt我编辑了我的问题并更新了一条:你的建议允许在我的应用程序播放声音时播放来自不同应用程序的音乐,但一旦屏幕关闭或应用程序进入后台,我的应用程序声音就会停止。有什么想法吗?让我们调试一下。如果您(暂时)放弃了可混合性的想法,而不使用可混合选项,会发生什么。你只需要播放,简单明了。你的声音在背景中继续吗?另外请看我对我的答案的新编辑,因为我有点担心你可能对背景声音的含义有错误的理解。