在有些應(yīng)用中需要用到背景音樂和音效,那在程序中是這么實現(xiàn)的。
1.首先加載背景音樂需要用到AVFoundation框架
2.音樂資源都是在包里的,所以需要獲得包路徑,涉及方法- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
url其實就是包地址,可以通過[[NSBundlemainBundle]pathForResource:@"背景音樂" ofType:@"caf"];獲得到路徑path,然后用NSURL的fileURLWithPath方法將path轉(zhuǎn)化為url;
3.設(shè)置音樂播放次數(shù).numberOfLoops。設(shè)為0僅播放一次;設(shè)為1則循環(huán)1次播放2次;設(shè)為-1則循環(huán)播放不間斷;
4.設(shè)置音樂聲音大小.volume。
5.準備播放,調(diào)用方法 PRepareToPlay。
6.開始播放,調(diào)用方法 play;停止播放:stop;
NSString *path = [[NSBundle mainBundle]pathForResource:@"背景音樂" ofType:@"caf"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil]; player.numberOfLoops = -1; player.volume = 0.5f; [player prepareToPlay]; [player play];
而加載音效則需要用到AudioToolbox框架,和音樂一樣需要加載包路徑,使用的方法是AudioServicesCreateSystemSoundID,這是個c語言的方法,其中傳入的url需要用到__bridge進行轉(zhuǎn)換,傳出一個SystemSoundID來提供播放的時候調(diào)用,播放使用的方法是AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID) 。
NSString *path = [[NSBundle mainBundle]pathForResource:soundFileName ofType:nil]; NSURL *url = [NSURL fileURLWithPath:path]; SystemSoundID soundID; AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID); AudioServicesPlaySystemSound(soundID);
此外還有個方法是AudioServicesPlayAlertSound,此方法在播放音效的同時會發(fā)出震動,給用戶提醒。
新聞熱點
疑難解答