2016-09-14 77 views
-2

我已經下載了一個mp3文件,但是我無法播放它。該文件被下載,我已經檢查過,但是當我嘗試播放本地文件時,沒有任何反應。如果我直接播放而不下載它,它會播放。從網址下載並播放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]; 
} 

回答

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]; 
}