In my init method I initialise the sound_a.wav like this.
AVAudioPlayer *snd = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle]
URLForResource:@"sound_a" withExtension:@"wav"] error: nil];
Depending on the scenario I need to play a different sound (let's assume that sound is sound_b).
What code do I need to change this on the fly?
First if AVAudioPlayer
still playing, stop it:
if([snd isPlaying]){
[snd stop];
}
Then, recreate new AVAudioPlayer
with new URL. My first suggestion to reinit the player will not work. You have to create a new instance.
snd = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"sound_b" withExtension:@"wav"] error: nil];
[snd play];
Better solution is to use AVQueuePlayer for multiple sounds:
AVPlayerItem *item1 = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"sound_a"]];
AVPlayerItem *item2 = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"sound_b"]];
AVQueuePlayer *player = [[AVQueuePlayer alloc] initWithItems:@[item1, item2]];
[player play];
[...]
[player advanceToNextItem];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With