Search code examples
iosmultimedia

How to Play multiple audio files simultaneously


how to Play numbers Of audio files at same time With AVAudioPlayer? Is it Possible to Play numbers Of audio files can play at same time using AVAudioPlayer? or any other way to play numbers of audio files at same time ? Thank You!


Solution

  • Files with below formats can be played simultaneously on iPhone.

    AAC, MP3, and ALAC (Apple Lossless) audio: have CPU resource concern. Linear PCM and IMA/ADPCM (IMA4 audio): without CPU resource concerns.

    You just need to create a new player instance for every music file, that you want to play.

    Sample Code snippet:

    -(void)playSounds{
        [self playSound1];
        [self playSound2];
    }
    
    -(void)playSound1{
        NSString *path = [[NSBundle mainBundle] pathForResource:@"file1" 
                                                          ofType:@"m4a"];  
        AVAudioPlayer* player= [[AVAudioPlayer alloc] initWithContentsOfURL:
                                                     [NSURL fileURLWithPath:path]
                                                                      error:NULL];  
        player.delegate = self;  
        [player play];
    }
    
    -(void)playSound2{
         SString *path = [[NSBundle mainBundle] pathForResource:@"file2" 
                                                          ofType:@"m4a"];  
        AVAudioPlayer* player= [[AVAudioPlayer alloc] initWithContentsOfURL:
                                                     [NSURL fileURLWithPath:path]
                                                                      error:NULL];  
        player.delegate = self;  
        [player play];
    }
    

    Convert to supported format (i.e. mp3 to caf):

    /usr/bin/afconvert -f caff -d ima4 sound.mp3 sound.caf

    Detailed tutorial:

    https://brainwashinc.wordpress.com/2009/08/14/iphone-playing-2-sounds-at-once/