How to Play two audio files together in iOS

2020-03-08 05:37发布

I am working on one of the application with sound files. In this application there is one slider implementation. On the basis of slider ratio all files will be handled to set sound volume. But with this volume effect there will be a sound combination of two different sets of files suppose there are sound set of fiel A & B.

There will be a combination of 75% of A file & 25% of B file.

标签: iphone
2条回答
够拽才男人
2楼-- · 2020-03-08 06:28

You can achieve it the straightforward way, initing 2 avaudioplayers sequentially, they will play together :

{
...
    NSString *songA = [[NSBundle mainBundle] pathForResource:@"songA" ofType:@"mp3"];
    NSError *soundError = nil;
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:songA] error:&soundError];
    if(self.player == nil)
        NSLog(@"%@",soundError);
    else
    {
        [self.player setDelegate:self];
        [self.player setVolume:0.75];
        [self.player play];
    }

    NSString *songB = [[NSBundle mainBundle] pathForResource:@"songB" ofType:@"mp3"];
    soundError = nil;
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:songB] error:&soundError];
    if(self.player == nil)
        NSLog(@"%@",soundError);
    else
    {
        [self.player setDelegate:self];
        [self.player setVolume:0.25];
        [self.player play];
    }
...
}
查看更多
男人必须洒脱
3楼-- · 2020-03-08 06:29

In Apple's Doc

Playing Multiple Sounds Simultaneously

To play multiple sounds simultaneously, create one playback audio queue object for each sound. For each audio queue, schedule the first buffer of audio to start at the same time using the AudioQueueEnqueueBufferWithParameters function.

Starting in iOS 3.0, nearly all supported audio formats can be used for simultaneous playback—namely, all those that can be played using software decoding, as described in Table 1-1. For the most processor-efficient multiple playback, use linear PCM (uncompressed) or IMA4 (compressed) audio.

I think you'll gonna need to invoke Audio Queue

Here's the reference of Audio Queue

For setting volumes to 75% of A and 25% of B, you can use OpenAL to achieve this.

查看更多
登录 后发表回答