tags:

views:

129

answers:

2

Hi,

We want to create an application that downloads a mp3 file and then starts to play it.

Has anyone an idea of how to download the mp3 file from an url and then store it, either on the iphone or in the application (depending on what is possible).

+1  A: 

Add the following import statement to your header:

#import <AVFoundation/AVFoundation.h>

In your implementation somewhere:

NSError *error;
NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://xyz/abc.mp3"]];

audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
audioPlayer.numberOfLoops = -1;
audioPlayer.delegate = self;
audioPlayer.volume = 1.0f;
[audioPlayer prepareToPlay];

if (audioPlayer == nil)
    NSLog(@"%@", [error description]);
else
    [audioPlayer play];

Don't forget to release the player at some point:

[audioPlayer release];
Alex Reynolds
A: 

dirt simple, on a thread:

myMP3 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://..."]];

slightly less simple, but with more options:

[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://..."]] delegate:self];

Or just play it directly:

[[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://..."] error:nil] play];

Edit: the above snippet would leak. You should store the created AVAudioPlayer instance in a member and release it when the audio finishes playing or you are otherwise done with it. I do not know off hand if releasing a playing AVAudioPlayer stops the audio.

drawnonward
That last statement will create a memory leak.
Alex Reynolds
...if you don't `release` it, that is.
Jacob Relkin
You might add an `autorelease` in there.
Alex Reynolds