bruno bruno - 1 year ago 104
Objective-C Question

Download and play mp3 file from URL

I have downloaded a mp3 file but i'm not able to play it. The file is downloaded, i've checked but when i try to play the local file, nothing happens. If i directly play it without downloading it, it plays.

- (IBAction)downloadTrack:(id)sender {

NSData *soundData = [NSData];
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documents];
[soundData writeToFile:filePath atomically:YES];

NSURL *urlFile = [NSURL URLWithString:filePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:urlFile error:nil];
player.numberOfLoops = -1; //Infinite

[player play];

Answer Source
- (void)viewDidLoad
    [super viewDidLoad];

    // Download
    NSString *urlString = @"";
    NSURL *url = [[NSURL alloc] initWithString:urlString];
    NSData *soundData = [NSData dataWithContentsOfURL:url];
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [documents stringByAppendingPathComponent:@"Ola.mp3"];
    [soundData writeToFile:filePath atomically:YES];

    // Play
    NSString *filename = @"Ola.mp3";
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentsDirectory = [pathArray objectAtIndex:0];
    NSString *yourSoundPath = [documentsDirectory stringByAppendingPathComponent:filename];

    NSURL *soundUrl;
    if ([[NSFileManager defaultManager] fileExistsAtPath:yourSoundPath])
        soundUrl = [NSURL fileURLWithPath:yourSoundPath isDirectory:NO];

    // Create audio player object and initialize with URL to sound
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
    [_audioPlayer play];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download