声音
1.声音需要导入AVFoundation框架。
#import <AVFoundation/AVFoundation.h>
2.需要从Bundle(即app包下的资源)或则本地以及网络资源加载文件,prepareToPlay准备播放
//设置背景音乐
NSString *path=[[NSBundle mainBundle] pathForResource:@"背景音乐" ofType:@"caf"];
//注意路径转成url的时候 本地的用fileUrlwithPath 网络的用URLwithstring
NSURL *url=[NSURL fileURLWithPath:path];
_soundPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[_soundPlayer setVolume:0.2f];
//设置准备播放在播放效果比较好 提前准备下
[_soundPlayer prepareToPlay];
音效
1.需要导入AudioToolBox矿建
#import <AudioToolbox/AudioToolbox.h>
2.使用C语言直接将音频加入到内存,通过SystemSoundID来播放。
3.播放的时候控制不了音量也暂停不了。
4.效率高,通常播放时间段的音频,一般不超过2秒。
5.通常为了避免同一个音效文件在不同的控制器中被重复加载,造成无谓的内存消耗,在使用音效的时候,通常使用数据字典来保存创建的SoundID,根据是否存在SoundID在判断是否加载音频文件。
-(SystemSoundID)loadSound:(NSString *)name{
NSString *path=[[NSBundle mainBundle] pathForResource:name ofType:nil];
NSURL *url=[NSURL fileURLWithPath:path];
//SystemSoundID不是一个指针类型 所以传他的地址进去
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
return soundID;
}
AudioServicesPlayAlertSound(_pingSoundID); 关闭提示音是可以关闭的
AudioServicesPlayAlertSound(_sucessfulSoundID); 有震动 关闭不了的