У меня есть приложение, которое постоянно получает целочисленные данные от датчика Bluetooth, и я сделал это так, чтобы, если целое число меньше 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)")
}
}