我有一个不断从蓝牙传感器接收整数数据的应用程序,我这样做,如果整数小于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)")
}
}
答案 0 :(得分:1)
如果音频播放器已播放(isPlaying
),请勿开始播放!
https://developer.apple.com/reference/avfoundation/avaudioplayer/1390139-isplaying
答案 1 :(得分:0)
我相信AVAudioPlayer有一个委托方法来检查音频是否已经播放完毕:
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
// ----------------------------------------------
// set your custom boolean flag 'isPlayingAudio'
// to false so you can play another audio again
// ----------------------------------------------
}
...
-(void)monitorBluetoothNumber
{
if(bluetoothNumber < 50 && !self.isPlayingAudio)
{
[self playMusic];
self.isPlayingAudio = YES;
}
}
您需要设置音频播放器并明确设置其代理。
代码是Objective C,但您可以轻松适应Swift。