AVAudioPlayer changes audio URLs on the fly

In my init method, I initialize sound_a.wav as follows.

    AVAudioPlayer *snd = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] 
    URLForResource:@"sound_a" withExtension:@"wav"] error: nil];

Depending on the scenario, I need to play another sound (let it be assumed that the sound is sound_b).

What code do I need to change on the fly?

+4
source share
3 answers

First, if AVAudioPlayerstill playing, stop it:

if([snd isPlaying]){
    [snd stop];
}

Then recreate a new one AVAudioPlayerwith a new URL. My first suggestion about reactivating the player will not work . You need to create a new instance.

snd = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"sound_b" withExtension:@"wav"] error: nil];
[snd play];

The best solution is to use AVQueuePlayer for several 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];
+4
source

, "". , .

0

You can create instances of AVAudioPlayer for all the sounds you want to play, and use prepareToPlay to preload your buffers. Then, when you need to play another sound, just stop the previous player using the method stopand play another player (for the next sound) with playAtTime:.

0
source

All Articles