【发布时间】:2014-11-29 08:38:46
【问题描述】:
我收到以下错误:
[0x19bf89310] AVAudioSession.mm:646: -[AVAudioSession setActive:withOptions:error:]: 停用正在运行 I/O 的音频会话。在停用音频会话之前,应停止或暂停所有 I/O。
我已经阅读了这篇文章:
但是那里的解决方案并没有解决我的问题。即:
- 小应用(游戏)
- AudioHelper.swift 中处理的音频背景音乐
- 使用
SKActino.playSoundFile播放的其他“blip”声音
复制
- 开始游戏(背景音乐开始播放)
- 结束游戏(音乐停止)
- 重启游戏(音乐再次响起)
- 出现上述错误
- SKAction.playSoundFile 不再总是有效(有些有效,有些无效)
我的音频处理代码(又名 AudioHelper.swift)
class AudioHelper: NSObject, AVAudioPlayerDelegate {
var player : AVAudioPlayer?
class var defaultHelper : AudioHelper {
struct Static {
static let instance : AudioHelper = AudioHelper()
}
return Static.instance
}
override init() {
super.init()
}
func initializeAudio() {
var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound_float", ofType: ".mp3")!)
self.player = AVAudioPlayer(contentsOfURL: url, error: nil)
self.player?.numberOfLoops = -1
self.player?.play()
}
func stopAudio() {
self.player?.stop()
self.player?.prepareToPlay()
AVAudioSession.sharedInstance().setActive(false, error: nil)
}
func startAudio() {
AVAudioSession.sharedInstance().setActive(true, error: nil)
self.player?.play()
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
self.stopAudio()
}
}
我正在通过AppDelegate 初始化&暂停&开始
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
AudioHelper.defaultHelper.initializeAudio()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
AudioHelper.defaultHelper.stopAudio()
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
AudioHelper.defaultHelper.startAudio()
}
}
我哪里错了?
【问题讨论】:
-
只是一个提示 - 为这些事情创建管理器。将所有代码都放在 AppDelegate 中,您违反了许多标准并失去了可读性。
-
@kpsharp 将所有内容移至帮助程序。仍然出现相同的错误 - 请参阅上面的更新代码:/
-
想通了 - 必须移动 setActive(false)。现在它可以工作了(见自己的答案)。谢谢你调查它@kpsharp
-
我从没想过把它换给经理会解决它,我只是注意到这是你应该改变的一件事。干得好,伙计。很高兴看到您没有放弃它,而是一直在自己寻找答案。我们需要更多像你这样的人。
-
另外,接受您自己的答案以供人们查看。谢谢。
标签: ios swift sprite-kit avaudioplayer avaudiosession