我需要用4-5个旋律创建一个音频播放器

时间:2011-03-11 09:18:13

标签: iphone cocoa-touch avaudioplayer avfoundation

我是Iphone SDK编程的新手 我需要创建音频播放器,但没有阵列。旋律的名称为“sound1,sound2,sound3 ......”

我的代码在这里:

NSUInteger x;
for (x=1; x<=tuneNums; x++)
{
    path = [[NSBundle mainBundle] pathForResource:@"sound%d" ofType:@"wav"];
    if([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        aSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
        [aSound setNumberOfLoops:0];
        aSound.delegate = self; 
        [aSound prepareToPlay];
    }       
}

我有所有按钮并且工作得很好,但只有一个mellody :(但是如何释放4-5旋律我不知道:(

P.S。原谅我的英语我刚刚离开西伯利亚

2 个答案:

答案 0 :(得分:0)

如果我说得对,你应该添加方法 -

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [player release];
}

并且不要忘记将视图控制器设置为播放器代理。

aSound.delegate=self;

答案 1 :(得分:0)

你在每个周期分配一个AVAudioPlayer,你只得到一个'旋律',因为这是在最后一个周期中分配的那个。

正如7KV7指出的那样,当用户按下按钮时,你应该分配一个AVAudioPlayer,播放相应的音频文件,然后在按下另一个按钮时释放/重新创建它。

类似的东西:

- (void)button1Pressed:(id)sender {
    // release the current player
    if(aSound) {
        [aSound release], aSound = nil;
    }

    // create a new player with the first file
    aSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
    [aSound setNumberOfLoops:0];
    aSound.delegate = self; 
    [aSound prepareToPlay];
}

如何确定按下按钮时要播放的音频文件取决于您。如果您只有四个音频文件,最简单的方法是使用固定数量的buttonPressed选择器(例如button1Pressed,button2Pressed)并将它们与您的四个按钮相关联。