Check if Audio is playing in the App

2019-06-14 14:00发布

问题:

I've been working on that for 3 hours already, and i can't find a solution to it. I am using a 3rd Party library, that plays a sound for me, I am guessing they are using AVAudioPlayer playSound, and i want to know, if there is a way to know if my app is playing a sound.

I don't have access to the 3rd Party library, and the property to play that sound is private. I've been trying AVAudioSession, but there's only two different ways to check if there is any sound playing, and unfortunately it can only check for sound coming from outside the app.

Thanks

回答1:

//Register self for remote notifications of play/pause toggle    
 //(i.e. when user backgrounds app, double-taps home,   
  //then swipes right to reveal multimedia control buttons).  
   //See MyWindow.h for more info.     

Add this Notification Center where to detect playback

[[NSNotificationCenter defaultCenter] addObserver:self                                              selector:@selector(toggling_Playback)                                                  name:@"TogglePlayPause" object:nil]; 

- (void)toggling_Playback {     
     (self.player.isPlaying ? [self.player pause] : [self.player play]); 
}


AVAudioPlayerDelegate protocol methods: 

 - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)p successfully:(BOOL)flag { 
    [self.player stop];        
  [self ffButtonWasPressed];  
   } 

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {    
 //In real app, may persist this to NSUserDefaults to act on after interruption ends  
   //or app resumes.    
 NSLog(@"Interruption began"); 

} 

//Note: this form is only for iOS >= 4.0. See docs for pre-4.0.

 - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags { 
    NSLog(@"Interruption ended");   
  //restart playback if flag indicates we should resume 
    if (flags & AVAudioSessionInterruptionFlags_ShouldResume)     {    
     [self toggling_Playback];    
 } 
}

If you still have any doubt: kindly refer this link http://www.allappsdevelopers.com/TopicDetail.aspx?TopicID=99cb8bf0-91ac-4c41-a903-2dc744444b7a