Stop AVAudioPlayer

here is my code

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"95" ofType:@"wav"]; NSError *activationError = nil; NSError *audioPlayerInitError = nil; [[AVAudioSession sharedInstance] setActive: YES error:&activationError]; NSURL *newURL = [NSURL fileURLWithPath:soundFilePath]; musicPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError]; if (musicPlayer1) { [musicPlayer1 stop]; [musicPlayer1 release]; musicPlayer1 = nil; } else { [musicPlayer1 prepareToPlay]; [musicPlayer1 setVolume:.8]; [musicPlayer1 setNumberOfLoops:-1]; // -1 means play indefintely [musicPlayer1 setDelegate: self]; [musicPlayer1 play]; } 

}

I am going to start and stop AVAudioPlay with the same button (musicPlayer1 is in the header). Now, when I touch the button, it does not play anything. Help me please?

+1
source share
1 answer

Each time create a new instance of AVAudioPlayer . You need to hold the link to the object somewhere and return to this question. Add a field to the view controller class:

 @private AVAudioPlayer *currentAudio; 

And then in this method make the following changes:

 if (currentAudio) { [currentAudio stop]; [currentAudio release]; currentAudio = nil; } else { // what you already have goes here } 
+3
source

Source: https://habr.com/ru/post/1369681/


All Articles