Chaudhry Talha Chaudhry Talha - 4 years ago 114
iOS Question

Unable to play sound via URL in AVAudioPlayer

I've looked and applied almost all the solutions given on StackOverflow but it is not working for me. Here is my code:

NSString *path = [NSString stringWithFormat:@"http://www.schillmania.com/projects/soundmanager2/demo/_mp3/rain.mp3"];
NSURL *soundUrl = [NSURL fileURLWithPath:path];

_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

[_player play];


Based on other answers in similar questions I've also made
@property (strong, nonatomic) AVAudioPlayer *player;
but it still doesn't work. What am I doing wrong?

Based on a comment I've also tried this:

NSURL *url = [[NSURL alloc]initWithString:@"http://www.schillmania.com/projects/soundmanager2/demo/_mp3/rain.mp3"];
AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:url];
AVPlayer *pla = [[AVPlayer alloc]initWithPlayerItem:item];
[pla play];


But still it's not playing!

Answer Source

As @paiv says, AVAudioPlayer won't download your file from the internet. NSURLs are used for local files as well as for internet resources, and in this case the sound must be a local file. You will need to download the file first, then play it. No, you can't use AVPlayer either. You will need to download the file (probably by using NSURLSession and and NSURLSessionDownloadTask) and then play the sound once the file download is complete.

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