从 URL 下载并播放 mp3 文件

Download and play mp3 file from URL

我下载了一个 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];
}
- (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];
}