开发者

stopping an AVAudioPlayer

开发者 https://www.devze.com 2023-02-21 17:08 出处:网络
here is my code NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@\"95\" ofType:@\"wav\"];

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 fileURLWithPat开发者_如何学Goh: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?


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号