Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer change sound URL on the fly

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?

like image 249
cateof Avatar asked Apr 17 '15 11:04

cateof


1 Answers

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];
like image 99
dieter Avatar answered Sep 22 '22 12:09

dieter