开发者

Sounds playing over each other using AVAudioPlayer

开发者 https://www.devze.com 2023-02-13 00:46 出处:网络
Right, sorry if i seem like a noob, but i\'m new to xcode. I\'m currently making a soundboard, and i\'ve got all the buttons to work and play sounds from them.

Right, sorry if i seem like a noob, but i'm new to xcode. I'm currently making a soundboard, and i've got all the buttons to work and play sounds from them.

However, if one sound is playing, when i press another button, rather than stopping the original sound, it just plays over it, so i was wandering if anyone knew开发者_JS百科 how to fix this?

Here's the code i'm using for the buttons:

- (IBAction)playsound {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Gold" ofType:@"mp3"];
    AVAudioPlayer* myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    myAudio.delegate = self;
    myAudio.volume = 2.0;
    myAudio.numberOfLoops = 0;
    [myAudio play];
}

I'd be really grateful if someone could help me out.

Thanks.


If the other sound is still playing, you need to tell it to stop. You probably want to look into using the calling the stop method on the other AVAudioPlayer. So, something like where you have:

[myAudio play];

...insert a method call just before that to tell the other sound to stop.

[myOtherAudioThatsPlaying stop];
[myAudio play];

It might make sense to also browse the AVAudioPlayer documentation.


While bobtiki's answer is formally correct, it only makes sense to call the stop method if you want to do something useful with the sound after it has stopped, for example start playing it again. Since you just want to get rid of it, I recommend have the player just get deallocated, which automatically makes the sound stop playing. So, instead of

AVAudioPlayer* myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

add an instance variable to your class:

AVAudioPlayer* myAudio;

then just use

  myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];

Everytime a new sound is played, myAudio gets assigned a new pointer and the old AVAudioPlayer just gets deallocated.

0

精彩评论

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