最近在总结项目里用到的技术,包括很早之前用的一些东西!有时间就总结总结在总结
下面通过网址下载音频缓存到本地
主要的思路就是从服务器上下载音频缓存本地,然后同一个视频再次下载是先判断本地,如果有取出来,如果没有在下载,当然我们是下载一个 amr 的转成 war 的病缓存到本地
二话不说上代码
DownloadAudioService.h
typedef void(^FinishBlock)(NSString *filePath);
typedef void(^Failed)();
@interface DownloadAudioService : NSObject
/*
* url 音频网址
* directoryPath 存放的地址
* fileName 要存的名字
*/
+ (void)downloadAudioWithUrl:(NSString *)url
saveDirectoryPath:(NSString *)directoryPath
fileName:(NSString *)fileName
finish:(FinishBlock )finishBlock
failed:(Failed)failed;
DownloadAudioService.m
//这个就不用接介绍了大家都熟悉
AFNetworking.h
//这个是转换音频格式的
VoiceConverter.h
amrFileCodec.h
+ (void)downloadAudioWithUrl:(NSString *)url
saveDirectoryPath:(NSString *)directoryPath
fileName:(NSString *)fileName
finish:(FinishBlock )finishBlock
failed:(Failed)failed
{
NSString *file_path = [directoryPath stringByAppendingPathComponent:fileName];
NSFileManager *fm = [NSFileManager defaultManager];
/// 判断文件是否已经存在
if ([fm fileExistsAtPath:file_path])
{
finishBlock(file_path);
}
/// 不存在时
else
{
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//AFN3.0+基于封住URLSession的句柄
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//请求
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//下载Task操作
NSURLSessionDownloadTask *_downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//进度
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
// filePath就是你下载文件的位置,你可以解压,也可以直接拿来使用
NSString *armFilePath = [filePath path];// 将NSURL转成NSString
if ([DownloadAudioService amrToWavFrom:armFilePath to:file_path]) {
finishBlock(file_path);
}
else {
failed();
}
}];
[_downloadTask resume];
}
}
#pragma mark - amr格式转换wav格式
+(BOOL)amrToWavFrom:(NSString *)amrPath to:(NSString *)wavPath {
//转格式
return [VoiceConverter ConvertAmrToWav:amrPath wavSavePath:wavPath];
}