- 这里只是说说异步 单线程下载与文件的保存
- 以下载一个mp3文件并保存为例:
-
- -(void)loading
- {
-
- NSString *urlString = [NSString stringWithFormat:@"http://zhangmenshiting2.baidu.com/data2/music/14893666/14893666.mp3?xcode=f7e142418de081ff52f81344843b869a&mid=0.73830637514858"];//这里设置的是一个mp3的下载地址
- NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL, kCFStringEncodingUTF8 );
- NSURL *url =[NSURL URLWithString:encodedString];
-
-
- NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:5.0f];
- NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
- if (connection)
- {
- self.receivedData = [NSMutableData data];
- }
- else
- {
- NSLog(@"Bad Connection!");
- }
-
- [request release];
- [connection release];
- }
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- {
- [receivedData setLength:0];
- long long mp3Size = [response expectedContentLength];
- NSLog(@"%lld",mp3Size);
-
- }
-
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- {
- [receivedData appendData:data];
- }
-
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection
- {
- [connection cancel];
-
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDirectory = [paths objectAtIndex:0];
- NSLog(@"mp3 path=%@",documentsDirectory);
- NSString *filePath = [documentsDirectory stringByAppendingPathComponent: mp3Name];
-
-
- NSFileManager *fileManager = [NSFileManager defaultManager];
- [fileManager createFileAtPath:filePath contents:nil attributes:nil];
- NSLog(@"mp3 path=%@",filePath);
-
- [receivedData writeToFile:filePath atomically:YES];
-
-
- [self playVoice:filePath];
-
-
-
-
- }
-
- 简单的播放mp3文件的方法:
- 使用前要添加库:AudioToolbox.framework和AVFoundation.framework,
- #import <AVFoundation/AVFoundation.h>
- #import <AudioToolbox/AudioToolbox.h>
- -(void)playVoice:(NSString *)filePath
- {
-
- NSURL * musicURL= [[NSURL alloc] initFileURLWithPath:filePath];
-
-
- AVAudioPlayer * voicePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
- self.thePlayer = voicePlayer;
- [voicePlayer release];
-
- [musicURL release];
- [thePlayer setVolume:1];
- thePlayer.numberOfLoops = -1;
-
-
- [thePlayer play];
- }
posted @
2014-12-02 14:28
郑文亮
阅读(
1895)
评论()
编辑
收藏
举报