Fahad Ali Fahad Ali - 6 days ago 6
iOS Question

AVAudioPlayer Freezes the UI when new sound is played

I am new to iOS and I was searching fix for this issue since morning and didn't find the solution yet, I have more than 6000 sound files online which i want to play using

AVAudioPlayer
when user click on the cell, so i implemented it in
didSelectRowAtIndexPath:

like this :

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [soundsArray objectAtIndex:(int)indexPath.row]];
NSData *soundData = [NSData dataWithContentsOfURL:url];
_audioPlayer = [[AVAudioPlayer alloc] initWithData:soundData error:NULL];
[_audioPlayer play];
}


the problem is, whenever i click on any row, the whole UI freezes till the time it takes to load the complete sound file from internet,
for larger files , it takes longer.

I tried with
AVPlayer
and it is working fine, but I need
AVAudioPlayer
becouse it seems easy to me to work with
-(void)AVAudioPlayerDidFinishPlaying:(AVAudioPlayer *)Player successfully:(BOOL)flag


thats why I want to implement it with
AVAudioPlayer


I hope you understood my problem,
Sorry for my bad English.

Answer

Never use

 NSData *soundData = [NSData dataWithContentsOfURL:url];

this will block your UI.

You need to use NSURLSession to download data asynchronously.

Comments