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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章