iOS 設定鈴聲---載入音樂和音頻然後進行播放

來源:互聯網
上載者:User

標籤:

在有些應用中需要用到背景音樂和音效,那在程式中是這麼實現的。

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 設定鈴聲---載入音樂和音頻然後進行播放

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.