Fahad Ali Fahad Ali - 1 year ago 79
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

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

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
and it is working fine, but I need
becouse it seems easy to me to work with
-(void)AVAudioPlayerDidFinishPlaying:(AVAudioPlayer *)Player successfully:(BOOL)flag

thats why I want to implement it with

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

Answer Source

Never use

 NSData *soundData = [NSData dataWithContentsOfURL:url];

this will block your UI.

You need to use NSURLSession to download data asynchronously.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download