繁体   English   中英

如何以编程方式下载音频文件?

[英]How to download a audio file programmatically?

我想从以下链接下载音频文件

音频文件链接

我已经尝试过在此网站上发布的其他答案。 但是我不想使用ASIHTTPRequest,所以任何人都可以告诉我如何将链接内容下载到我的文档目录中。

好吧,你可以这样写:

//Download data
NSData *data = [NSData dataWithContentsOfURL:<YOUR URL>];

//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths  objectAtIndex:0];

//Save the data    
NSString *dataPath = [path stringByAppendingPathComponent:@"filename"];
dataPath = [dataPath stringByStandardizingPath];
BOOL success = [data writeToFile:dataPath atomically:YES];

您可以使用NSURLConnection将文件下载到内存 ,然后将其写入文件。

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:yourURL]
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                                              [data writeToFile:yourPath atomically:YES];
                                              // Audio file is ready to be played.
                                          }];

您也可以创建自己的NSOperationQueue实例以在后台执行写入。

如果文件很大,你不想把它全在内存中,你应该使用AFNetworking或者你也可以使用写自己的实现NSOutputStream直接写入到磁盘。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM