Search code examples
iosaudiomp3

iOS: how to conveniently store and play many mp3 files


I have a program with about 2000 short mp3 files. I am now storing all those file into folder Supporting Files and when I want to play I call this function:

-(void)playSound:(NSString *)mySoundFileName{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:mySoundFileName ofType:@"mp3"];  
    if ([NSData dataWithContentsOfFile:filePath]) {  
        url = [NSURL fileURLWithPath:filePath];
        audioPlayer = [[AVAudioPlayer alloc]
                           initWithContentsOfURL:url
                           error:nil];
        [audioPlayer play];  
    } 
}

However, the first time I play the sound, it always takes long time to search/load the file. More specifically, after pressing "play sound" button to play sound, I have to wait for at least 5 seconds until it plays. It is OK to play other sound after that, i.e, it play almost immediately when I press "play sound" button. Do you have any suggestion to store and play those many files more efficiently? Thank you very much


Solution

  • It can sometimes take an undesirable amount of time for AVAudioPlayer to start playing initially. A good way to solve this is to make the initial alloc/init before you call play. This way the player is ready to play before the user presses the play button. Additionally, calling [player prepareToPlay]; before play will help improve performance slightly.