iosobjective-cavaudioplayer

Download Audio file from URL and play it in iOS App


I have an URL which I get from JSON response, When I hit the URL in browser the file is downloaded, Now am wondering how can I play such URL which is a Download URL.I've been looking around many post But none of them could help me.

type of url am getting : http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1

Below is the code I tried.

  NSString *audio=[NSString stringWithFormat:@"%@.mp3",cell.url];
  NSLog(@"url:%@",audio);

  NSURL  *url = [NSURL fileURLWithPath:audio];
  NSData *soundData = [NSData dataWithContentsOfURL:url];
  NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                               NSUserDomainMask, YES) objectAtIndex:0]
                          stringByAppendingPathComponent:@"sound.caf"];
    [soundData writeToFile:filePath atomically:YES];
    NSError *error;
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
                                                           fileURLWithPath:filePath] error:&error];
    [_audioPlayer play];
    NSLog(@"error %@", error);

Solution

  • Try this:

        //download your audio file
        NSString *urlString = @"http://www.smartivr.in/sounds/voicemail/download/f77245d9-e7ee-4424-850c-6a45022d0a54_1.mp3";
        NSURL  *url = [NSURL fileURLWithPath:urlString];
        NSData *soundData = [NSData dataWithContentsOfURL:url];
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask, YES) objectAtIndex:0]
                              stringByAppendingPathComponent:@"sound.caf"];
        [soundData writeToFile:filePath atomically:YES];
    
        // get the file from directory
        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
        NSString *documentsDirectory = [pathArray objectAtIndex:0];
        NSString *soundPath = [documentsDirectory stringByAppendingPathComponent:@"sound.caf"];
    
        NSURL *soundUrl;
        if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath])
        {
            soundUrl = [NSURL fileURLWithPath:soundPath isDirectory:NO];
        }
    
        // play audio file
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
        [audioPlayer prepareToPlay];
        [audioPlayer play];
    

    You should download your audio file asynchronously.