AVAudioPlayer 监听下载进度
时间: 2023-07-07 18:43:06 浏览: 61
AVAudioPlayer 本身并不支持下载功能,如果需要监听下载进度,可以使用 NSURLSession 来进行下载,并通过 AVAudioPlayer 播放下载好的音频文件。
具体来说,可以在 NSURLSessionDelegate 协议中实现以下方法:
```
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
// 将下载好的文件剪切到指定目录
NSString *destinationPath = [self getDestinationPathForDownloadedFile];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if ([fileManager fileExistsAtPath:destinationPath]) {
[fileManager removeItemAtPath:destinationPath error:nil];
}
BOOL success = [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:destinationPath] error:&error];
if (success) {
// 下载完成,发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"AVAudioPlayerDownloadProgressNotification" object:nil userInfo:@{@"progress":@(1.0)}];
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
// 发送下载进度通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"AVAudioPlayerDownloadProgressNotification" object:nil userInfo:@{@"progress":@(progress)}];
}
```
在上面的代码中,我们实现了 NSURLSessionDelegate 协议中的两个方法。在 didFinishDownloadingToURL 方法中,我们将下载好的文件从临时目录剪切到指定目录,并发送下载进度为 1.0 的通知。在 didWriteData 方法中,我们计算出当前的下载进度,并将其作为 userInfo 传递给通知中心。
在 AVAudioPlayer 播放音频文件之前,可以先判断文件是否已经下载完成,如果下载完成,则直接使用 AVAudioPlayer 播放文件,如果未完成,则等待下载完成之后再进行播放。在接收到下载进度通知之后,可以更新 UI 上的下载进度条。