start playing audio from a background task via AVAudioPlayer in Xcode

前端 未结 5 1071
小鲜肉
小鲜肉 2021-02-03 14:46

I am trying to start playing a sound from a background task via an AVAudioPlayer that is instantiated then, so here\'s what I\'ve got.

For readability I cut out all user

5条回答
  •  滥情空心
    2021-02-03 15:14

    What fixed it for me was to start playing some audio just as application quits, so I added 1sec blank audio in applicationWillResignActive in the AppDelegate

    func applicationWillResignActive(_ application: UIApplication) {
    
            self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
                self.endBackgroundUpdateTask(true)
            })
    
    
            let secSilence = URL(fileURLWithPath: Bundle.main.path(forResource: "1secSilence", ofType: "mp3")!)
    
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: secSilence)
            }
            catch {
                print("Error in loading sound file")
            }
    
            audioPlayer.prepareToPlay()
            audioPlayer.play()
    
    
    
    }
    

提交回复
热议问题