iOS_音频下载

下载方法一:

        //设置下载链接
        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");
            }
        }



下载好的音频保存在沙河的document文件夹下

打开沙河可以看到:


若下载的音乐文件太小,请检查一下链接是否正确。我之前也是因为链接给错,下下来的music.mp3都只有1k,后来链接给对了就有3M了。上面的链接百度找的,目前可用,若不可用请自行搜索找一个。

发布了29 篇原创文章 · 获赞 8 · 访问量 9万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章