从URL下载并播放mp3文件

时间:2016-09-14 15:42:57

标签: ios objective-c mp3 avaudioplayer

我已经下载了一个mp3文件,但我无法播放它。文件已下载,我已经检查但是当我尝试播放本地文件时,没有任何反应。如果我直接播放它而不下载它,它就会播放。

- (IBAction)downloadTrack:(id)sender {

    NSData *soundData = [NSData dataWithContentsOfURL:self.song.ticket.url];
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [documents stringByAppendingPathComponent:self.song.slug];
    [soundData writeToFile:filePath atomically:YES];

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

    [player play];
}

1 个答案:

答案 0 :(得分:2)

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Download
    NSString *urlString = @"https://oi.net/songs/5-dope-ski-128k.mp3";
    NSURL *url = [[NSURL alloc] initWithString:urlString];
    NSData *soundData = [NSData dataWithContentsOfURL:url];
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [documents stringByAppendingPathComponent:@"5-dope-ski-128k.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];
}
相关问题