简体   繁体   English

在iOS设备上同时播放声音

[英]Playing sounds simultaneously on iOS devices

I have 10 sounds in one view. 我在一个视图中有10个声音。 And they all play, however only one sound can play at a time. 他们都玩,但一次只能播放一种声音。 I want it so you can tap the sounds you want to play, and they all play at the same time. 我想要它,这样你就可以点击你想要播放的声音,它们都可以同时播放。 But at the moment when you press a sound it plays, then you go to press another sound and the sound previously stops. 但是当你按下它播放的声音时,你会按下另一个声音然后声音停止。

Here is the code which I have used for the sounds 这是我用于声音的代码

- (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];   

}

Thanks! 谢谢!

This probably causes the problem: 这可能会导致问题:

if (theAudio) [theAudio release];

The AVAudioPlayer cannot continue playing after it's released. AVAudioPlayer在发布后无法继续播放。

What basically happens: 基本上发生了什么
- Button click - 按钮单击
- theAudio is initialized - theAudio被初始化
- theAudio starts playing - theAudio开始播放
- Another button click - 另一个按钮点击
- theAudio is released and therefor stops playing - theAudio被释放,因此停止播放
- theAudio is initialized with another sound - theAudio用另一种声音初始化
- theAudio starts playing - theAudio开始播放

Seems like your theAudio is global and you instantiate it again in each method. 看起来你的theAudio是全局的,你可以在每个方法中再次实例化它。 Transform it in a local variable or define 3 (or how many you need). 将其转换为局部变量或定义3(或您需要多少)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM