聲音
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); 有震動 關閉不了的