標籤:
在有些應用中需要用到背景音樂和音效,那在程式中是這麼實現的。
1.首先載入背景音樂需要用到AVFoundation架構
2.音樂資源都是在包裡的,所以需要獲得包路徑,涉及方法- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
url其實就是包地址,可以通過[[NSBundlemainBundle]pathForResource:@"背景音樂" ofType:@"caf"];獲得到路徑path,然後用NSURL的fileURLWithPath方法將path轉化為url;
3.設定音樂播放次數.numberOfLoops。設為0僅播放一次;設為1則迴圈1次播放2次;設為-1則迴圈播放不間斷;
4.設定音樂聲音大小.volume。
5.準備播放,調用方法 prepareToPlay。
6.開始播放,調用方法 play;停止播放:stop;
1 NSString *path = [[NSBundle mainBundle]pathForResource:@"背景音樂" ofType:@"caf"];2 NSURL *url = [NSURL fileURLWithPath:path];3 AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];4 player.numberOfLoops = -1;5 player.volume = 0.5f;6 [player prepareToPlay];7 [player play];
而載入音效則需要用到AudioToolbox架構,和音樂一樣需要載入包路徑,使用的方法是AudioServicesCreateSystemSoundID,這是個c語言的方法,其中傳入的url需要用到__bridge進行轉換,傳出一個SystemSoundID來提供播放的時候調用,播放使用的方法是AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID) 。
1 NSString *path = [[NSBundle mainBundle]pathForResource:soundFileName ofType:nil];2 NSURL *url = [NSURL fileURLWithPath:path];3 SystemSoundID soundID;4 AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);5 6 AudioServicesPlaySystemSound(soundID);<br>
此外還有個方法是AudioServicesPlayAlertSound,此方法在播放音效的同時會發出震動,給使用者提醒。
iOS 設定鈴聲---載入音樂和音頻然後進行播放