在iOS设备上同时播放声音

时间:2011-04-14 20:42:01

标签: iphone objective-c cocoa-touch avaudioplayer

我在一个视图中有10个声音。他们都玩,但一次只能播放一种声音。我想要它,这样你就可以点击你想要播放的声音,它们都可以同时播放。但是当你按下它播放的声音时,你会按下另一个声音然后声音停止。

这是我用于声音的代码

- (IBAction)oneSound:(id)sender; {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"wav"];
    if (theAudio) [theAudio release];
    NSError *error = nil;
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (error)
        NSLog(@"%@",[error localizedDescription]);
    theAudio.delegate = self;
    [theAudio play];   


}



- (IBAction)twoSound:(id)sender; {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"wav"];
    if (theAudio) [theAudio release];
    NSError *error = nil;
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (error)
        NSLog(@"%@",[error localizedDescription]);
    theAudio.delegate = self;
    [theAudio play];   

}



- (IBAction)threeSound:(id)sender; {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"];
    if (theAudio) [theAudio release];
    NSError *error = nil;
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
    if (error)
        NSLog(@"%@",[error localizedDescription]);
    theAudio.delegate = self;
    [theAudio play];   

}

谢谢!

2 个答案:

答案 0 :(得分:2)

这可能会导致问题:

if (theAudio) [theAudio release];

AVAudioPlayer在发布后无法继续播放。

基本上发生了什么:
- 按钮单击
- theAudio被初始化了 - 音乐开始播放 - 另一个按钮点击
- theAudio被释放,因此停止播放 - 用另一种声音初始化音频 - theAudio开始播放

答案 1 :(得分:0)

看起来你的theAudio是全局的,你可以在每个方法中再次实例化它。将其转换为局部变量或定义3(或您需要多少)。

相关问题