stopping an AVAudioPlayer

2019-07-30 08:00发布

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条回答
相关推荐>>
2楼-- · 2019-07-30 08:33

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
}
查看更多
登录 后发表回答