下载方法一:
//设置下载链接
NSURL *soundURL = [NSURL URLWithString:@"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/99733412/87603531183600128.mp3?xcode=da76dbe4a83a8f23ffdc3037e7b25f97927dc57a6cb1af51&song_id=87603531"];
//根据链接获取数据
NSData *audioData = [NSData dataWithContentsOfURL:soundURL];
//设置保存文件夹
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//设置保存路径和生成文件名
NSString *filePath = [NSString stringWithFormat:@"%@/music.mp3",docDirPath];
//保存
if ([audioData writeToFile:filePath atomically:YES]) {
NSLog(@"succeed");
}else{
NSLog(@"faild");
}
下载方法二:
第二种方法网上的,开头部分稍微做了修改。这段可以显示下载的文件大小。
NSURL *soundURL = [NSURL URLWithString:@"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/99733412/87603531183600128.mp3?xcode=da76dbe4a83a8f23ffdc3037e7b25f97927dc57a6cb1af51&song_id=87603531"];
NSLog(@"soundURL:%@",soundURL);
NSDate *date = [NSDate date];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:soundURL];
NSURLResponse *response;
NSError *error;
NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSLog(@"Response expects %lld bytes", [response expectedContentLength]);
NSLog(@"Response suggested file name: %@", [response suggestedFilename]);
if ([response suggestedFilename])
// self.savePath = [DEST_PATH stringByAppendingString:[response suggestedFilename]];
if (!result)
NSLog(@"Error downloading data: %@.", [error localizedDescription]);
else if (response.expectedContentLength < 0)
NSLog(@"Error with download. Carrier redirect?");
else
{
NSLog(@"Download succeeded.");
NSLog(@"Read %d bytes", result.length);
NSLog(@"Elapsed time: %0.2f seconds.", -1*[date timeIntervalSinceNow]);
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/music.mp3",docDirPath];
if ([result writeToFile:filePath atomically:YES]) {
NSLog(@"succeed");
}else{
NSLog(@"faild");
}
}
打开沙河可以看到:
若下载的音乐文件太小,请检查一下链接是否正确。我之前也是因为链接给错,下下来的music.mp3都只有1k,后来链接给对了就有3M了。上面的链接百度找的,目前可用,若不可用请自行搜索找一个。