2016-09-14 3 views
-2

MP3 파일을 다운로드했지만 재생할 수 없습니다. 파일을 다운로드했는데 확인했는데 로컬 파일을 재생하려고하면 아무 일도 일어나지 않습니다. 다운로드하지 않고 직접 재생하면 재생됩니다.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]; 
} 

답변

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