stopping an AVAudioPlayer

2019-07-30 07:35发布

问题:

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 rying to start and stop the AVAudioPlay with the same button (musicPlayer1 is in the header). Now when i touch the button it does not play anything. Help please?

回答1:

You're creating a new instance of AVAudioPlayer each time. You need to hold onto the reference to the object somewhere, and refer back to that. Add a field to your 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
}