Swift 一次播放一个声音实例
我有一个应用程序,不断地从蓝牙传感器接收整数数据,我这样做,如果整数小于50,那么它应该播放MP3 问题是传感器非常快速地检查和发送整数,这导致了太多的音频实例,基本上mp3文件在同一时间被播放了太多次。如何让它在重新开始之前完成音频 这是主要代码:Swift 一次播放一个声音实例,swift,Swift,我有一个应用程序,不断地从蓝牙传感器接收整数数据,我这样做,如果整数小于50,那么它应该播放MP3 问题是传感器非常快速地检查和发送整数,这导致了太多的音频实例,基本上mp3文件在同一时间被播放了太多次。如何让它在重新开始之前完成音频 这是主要代码: var player: AVAudioPlayer? if let unwrappedString = Reading { let optionalInt = Int(unwrappedString)
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()
}
}
}
}
我相信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;
}
}
-(void)AudioPlayerDifinishPlay:(AVAudioPlayer*)播放器成功:(BOOL)标志
{
// ----------------------------------------------
//设置自定义布尔标志“isPlayingAudio”
//设置为false,以便可以再次播放另一个音频
// ----------------------------------------------
}
...
-(无效)监视器BluetoothNumber
{
如果(蓝牙编号<50&&!self.isPlayingAudio)
{
[自我播放音乐];
self.isPlayingAudio=是;
}
}
您需要设置音频播放器并设置其代理
代码是Objective C,但您可以轻松适应Swift。如果音频播放器已经在播放(
isplay
),请不要开始播放
-(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;
}
}