Chaudhry Talha
Chaudhry Talha

Reputation: 7898

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!

Upvotes: 0

Views: 360

Answers (2)

Duncan C
Duncan C

Reputation: 131481

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. 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.

EDIT:

As @Sneak pointed out in his comment below, AVPlayer is able to stream audio from the web, although I've actually never used that feature myself.

Upvotes: 2

Kuntal Gajjar
Kuntal Gajjar

Reputation: 802

I used this before and it is working fine for me

https://github.com/tumtumtum/StreamingKit

Upvotes: 0

Related Questions