我正在使用AFNetworking從服務器上下載音頻文件。該文件正在成功下載,因爲我可以通過進度模塊查看它。 我將它存儲在文檔目錄中,但後來無法播放它。 這裏是我的代碼: -下載音頻,無法使用AVAudioPlayer播放
-(void)downloadAudioFileFromUrl:(NSString *)str_url{
[SVProgressHUD show];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:str_url]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"momentsAudioToast.mp3"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Successfully downloaded file to %@", path);
[SVProgressHUD dismiss];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
[self playSound:path];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
[SVProgressHUD dismiss];
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
//[progressView setProgress: totalBytesWritten*1.0f/totalBytesExpectedToWrite animated: YES];
NSLog(@"downloaded %lld of %lld bytes and progress is %f", totalBytesWritten, totalBytesExpectedToWrite, totalBytesWritten*1.0f/totalBytesExpectedToWrite);
if(totalBytesWritten >= totalBytesExpectedToWrite)
{
//progressView.hidden = YES;
}
}];
[operation start];
}
- (void)playSound:(NSString *)path {
[self.player prepareToPlay];
//UIButton *audioButton = (UIButton *)sender;
//[audioButton setImage:[UIImage imageNamed:@"sound_preview.png"] forState:UIControlStateNormal];
NSData *audioData = [NSData dataWithContentsOfFile:path options: 0 error:nil];
self.player = [[AVAudioPlayer alloc] initWithData:audioData error:nil];
double duration = [self.player duration];
NSLog(@"%f", duration);
NSError * error;
self.player.delegate = self;
self.player.numberOfLoops = 0;
if (error) {
NSLog(@"Error: %@",[error description]);
}
else {
self.player.delegate = self;
[self.player play];
}
}
請幫助,如果我做錯了什麼。
在此先感謝。
我已經在第二方法中,如果([[的NSFileManager defaultManager] fileExistsAtPath:路徑])加入該條件和它返回真,仍持續時間來0.000。另外強烈的參考已經完成。請提出建議。 –