2015-04-17 88 views
3

在我的init方法中,我初始化sound_a.wav。AVAudioPlayer动态地更改声音网址

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

根据情景我需要播放不同的声音(让我们假设声音是sound_b)。

我需要什么代码才能在飞行中更改此代码?

+0

检查我的答案。 'AVQueuePlayer'可以帮助你 – dit

回答

0

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

3

首先,如果AVAudioPlayer还在玩,阻止它:

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

然后,重新创建新的AVAudioPlayer新的网址。 我的第一个建议重新启动播放器将不起作用。你必须创建一个新的实例。

更好的解决方法是使用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]; 
+0

看起来URL是只读的@property(只读)NSURL * url;/*返回nil如果对象不是用URL创建的*/ – cateof

+0

'[[NSBundle mainBundle] URLForResource:@“sound_b”withExtension:@“wav”]'? – dit

+0

这就是我所要求的,我可以更新URL吗? – cateof

0

您可以创建AVAudioPlayer的情况下为所有声音要播放和使用prepareToPlay预加载的缓冲区。然后,当您需要播放另一个声音时,请使用stop方法停止上一个播放器,然后使用playAtTime:播放另一个播放器(用于下一个声音)。

+0

为什么我需要playAtTime?播放声音很好,不是吗? – cateof

+0

这取决于你的需求。我建议你使用'playWithTime:',因为这个播放器可以先播放,并且会有不同的'currentTime'。在这种情况下,请调用'[player playWithTime:0]'从一开始播放。 –

+0

[player playWithTime:0]与[player play]相同,对吗? – cateof