AVAudioPlayer即时更改声音URL

cat*_*eof 5 iphone avaudioplayer ios

在我的init方法中,我像这样初始化sound_a.wav。

    AVAudioPlayer *snd = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] 
    URLForResource:@"sound_a" withExtension:@"wav"] error: nil];
Run Code Online (Sandbox Code Playgroud)

根据情况,我需要播放不同的声音(假设声音为sound_b)。

我需要即时更改哪些代码?

die*_*ter 5

首先如果AVAudioPlayer还在播放,停止它:

if([snd isPlaying]){
    [snd stop];
}
Run Code Online (Sandbox Code Playgroud)

然后,AVAudioPlayer使用新 URL重新创建 new 。我重新初始化播放器的第一个建议是行不通的。您必须创建一个新实例。

snd = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"sound_b" withExtension:@"wav"] error: nil];
[snd play];
Run Code Online (Sandbox Code Playgroud)

更好的解决方案是将AVQueuePlayer用于多个声音:

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];
Run Code Online (Sandbox Code Playgroud)


小智 0

不确定这里的“场景”是什么意思。但是,您可以通过创建一个包含声音列表的数组并每次生成一个随机索引来播放随机声音。