我试图在按下按钮时播放和循环播放铃声,并且在播放铃声时还运行其他逻辑。
在没有其他逻辑的情况下进行测试时,铃声会正常播放而不会被中断,但是在添加其他逻辑时会被打断。
如何避免这种干扰? 注意:铃声会播放一两秒钟,然后停止播放。
func makeVideoCall(callReceiverId : String) {
self.playSound(nameOfAudioFileInAssetCatalog: "outgoingRingtone2")
// Other logic/code executed here, like making calls to the backend and calling callKit functions
}
func playSound(nameOfAudioFileInAssetCatalog: String) {
//private
if let sound = NSDataAsset(name: nameOfAudioFileInAssetCatalog) {
do {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try self.soundPlayer = AVAudioPlayer(data: sound.data, fileTypeHint: AVFileTypeWAVE)
self.soundPlayer!.numberOfLoops = -1 // By setting to -1 the sound will be played infinitely, and will be stopped when the participant adds videotrack or when there is an error connecting the call
self.soundPlayer!.play()
} catch {
print("error initializing AVAudioPlayer")
}
}
}