文件的上载与保存,以及mp3文件的播放
文件的下载与保存,以及mp3文件的播放
这里只是说说异步 单线程下载与文件的保存 以下载一个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和NSURLConnection,并立即启动连接 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); } //接收NSMutableData数据 - (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];//mp3Name:你要保存的文件名称,包括文件类型。如果你知道文件类型的话,可以指定文件类型;如果事先不知道文件类型,可以在- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response中获取要下载的文件类型 //在document下创建文件 NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager createFileAtPath:filePath contents:nil attributes:nil]; NSLog(@"mp3 path=%@",filePath); //将下载的数据,写入文件中 [receivedData writeToFile:filePath atomically:YES]; //播放下载下来的mp3文件 [self playVoice:filePath]; //如果下载的是图片则可以用下面的方法生成图片并显示 create image from data and set it to ImageView /* UIImage *image = [[UIImage alloc] initWithData:recvData]; [imgView setImage:image]; */ } 简单的播放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;//设置音乐播放次数 -1为一直循环 //播放mp3,如果想要实现一些别的功能,可以看看AVAudioPlayer这个类,这里只是实现播放功能 [thePlayer play]; }