我在AFNetworking的帮助下从服务器下载音频文件。该文件已成功下载,因为我可以通过进度块查看它。 我将它存储在Documents目录中,但后来我无法播放它。 这是我的代码: -
-(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];
}
}
如果我做错了,请帮忙。
提前致谢。
答案 0 :(得分:0)
首先,确保您对AVAudioPlayer
实例player
保持强烈的引用,如下所示:
@property (nonatomic, strong) AVAudioPlayer *player;
第二,最有可能,这将是与路径相关的问题。尝试在播放时重建路径。
第三,,仔细检查文件是否存在,以及在任何音频播放器中播放时播放的文件。
答案 1 :(得分:0)
在您的情况下,如果您声明音频播放器完美。
并设置代表&如果从Web服务的音频文件中获取NSData。
然后您需要再插入一行代码并再次检查。
[self.player setVolume: 1.0];