2016-11-28 145 views
1

我有一個應用程序不斷接收來自藍牙傳感器的整數數據,並且我這樣做是爲了使整數小於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

我相信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。