gpt4 book ai didi

swift - 一次播放一个声音实例

转载 作者:行者123 更新时间:2023-11-28 06:29:19 25 4
gpt4 key购买 nike

我有一个不断从蓝牙传感器接收整数数据的应用程序,我这样做是为了在整数小于 50 时播放 MP3。

问题在于传感器正在非常快速地检查和发送整数,这导致音频实例过多,基本上是 mp3 文件同时播放了太多次。我怎样才能让它在重新开始之前完成音频?

这是主要代码:

var player: AVAudioPlayer?




if let unwrappedString = Reading {
let optionalInt = Int(unwrappedString)
if let upwrappedInt = optionalInt {
if(upwrappedInt < 50){
DispatchQueue.global(qos: .background).async {
self.playSound()

}
}
}
}

声音功能:

 func playSound() {
guard let url = Bundle.main.url(forResource: "beep1", withExtension: "mp3") else {
print("url not found")
return
}

do {
/// this codes for making this app ready to takeover the device audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)

/// change fileTypeHint according to the type of your audio file (you can omit this)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

// no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
player!.play()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}

最佳答案

如果音频播放器已经在播放(正在播放),请不要开始播放!

https://developer.apple.com/reference/avfoundation/avaudioplayer/1390139-isplaying

关于swift - 一次播放一个声音实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40836453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com