标签: ios Objective-C
发布时间: 2014/12/12 7:48:06
在我的项目我有 Url 的音频......看看我的代码...
ViewController.h
#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @interface ViewController : UIViewController<AVAudioPlayerDelegate,NSURLConnectionDelegate> { AVAudioPlayer *song; // NSMutableData *fileData; NSData *myData; } @property (nonatomic, retain) AVAudioPlayer *song; @property(nonatomic,retain) NSData *myData; @end
ViewController.m
#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize song,myData; - (void)viewDidLoad { [super viewDidLoad]; NSURL *myUrl; myUrl = [NSURL URLWithString:@"http://p0.bcbits.com/download/track/60523f9784a2912348eff92f7b7e21e8/mp3-128/1269403107?c22209f7da1bd60ad42305bae71896761f6cd1f4d6c29bf401ef7e97b90c3d5939b57f5479b37ad4d41c48227740d7ba8b5f79b76aa8d6735b8f87c781f44fb019762a2903fe65aeafb30d90cb56b385e27cd770cc9f9d60e5ea3f130da6ad3db728ff7e24a09fab9f351120810ee91f78f1e94fcabc98aabb37d4248358f6da4a0fa7a74fe8c89da2a768&fsig=cd06c325fc41b6f8edb0409011e8839c&id=1269403107&stream=1&ts=1395489600.0"]; myData = [NSData dataWithContentsOfURL:myUrl]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
在上面的代码如何可以将转换 mydata 到一个数组???或如何可以下载这个音频和在手机内存中存储??
您可以存储设备内存作为像下面将音频数据
myData = [NSData dataWithContentsOfURL:myUrl]; [myData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/audio.mp3"] atomically:YES];
要播放您保存在设备中的音频文件:
添加 AudioToolbox.framework
和 AVFoundation.framework
为您的项目生成
在.h 文件中
#import <AudioToolbox/AudioToolbox.h> #import <AVFoundation/AVFoundation.h> AVAudioPlayer *player;
在.m 文件
-(void)initPlayer { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride); NSError *err; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&err]; audioSession.delegate = self; [audioSession setActive:YES error:&err]; player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/audio.mp3"]] error:nil]; } -(void)playFile { if (player.playing) { [player pause]; isPlaying = NO; } else { [player play]; isPlaying = YES; } }
谢谢你 !
原文:http://my.oschina.net/u/2329800/blog/493456