iOS开发过程中可能会遇到播放音效的功能
其实很简单,iOS已经提供了一个框架直接负责播放音效 AudioToolbox.framework
新建项目 TestWeChatSounds
给新建的项目导入AudioToolbox.framework
导入成功之后如下图
项目目录如下
接下来我们给项目中添加几个caf格式的音效文件
接下来 我们打开 项目默认生成的ViewController中添加代码
导入 AudioToolbox
#import <AudioToolbox/AudioToolbox.h>
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIButton *btn1=[[UIButton alloc] initWithFrame:CGRectMake(20, 100, 120, 36)]; [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [btn1 setTitle:@"警告" forState:UIControlStateNormal]; [btn1 addTarget:self action:@selector(btn1Act) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn1]; UIButton *btn2=[[UIButton alloc] initWithFrame:CGRectMake(20, 150, 120, 36)]; [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [btn2 setTitle:@"错误" forState:UIControlStateNormal]; [btn2 addTarget:self action:@selector(btn2Act) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn2]; }
-(void)btn1Act { [self playSoundEffect:@"alarm.caf"]; } -(void)btn2Act { [self playSoundEffect:@"ct-error.caf"]; } -(void)playSoundEffect:(NSString *)name{ NSString *audioFile=[[NSBundle mainBundle] pathForResource:name ofType:nil]; NSURL *fileUrl=[NSURL fileURLWithPath:audioFile]; //1.获得系统声音ID SystemSoundID soundID=0; /** * inFileUrl:音频文件url * outSystemSoundID:声音id(此函数会将音效文件加入到系统音频服务中并返回一个长整形ID) */ AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID); //如果需要在播放完之后执行某些操作,可以调用如下方法注册一个播放完成回调函数 AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL); //2.播放音频 AudioServicesPlaySystemSound(soundID);//播放音效 // AudioServicesPlayAlertSound(soundID);//播放音效并震动 } void soundCompleteCallback(SystemSoundID soundID,void * clientData){ NSLog(@"播放完成..."); }
代码部分截图
好了 播放音效基本实现
下节我们讲一下播放音乐功能,有兴趣的可以继续学习 :http://blog.csdn.net/lwjok2007/article/details/50425324
代码我会上传群空间 【51228WeChatSounds.zip】
苹果开发群 :512298106 欢迎加入 欢迎讨论问题