簡體   English   中英

視圖加載時播放聲音

[英]Playing a Sound when view loads

我在以編程方式在iPhone上播放聲音時遇到問題-我不理解Xcode文檔中有關AvAudioPlayer的解釋。 可以請其他人給我一個代碼片段,或者更好地向我解釋一下嗎?

編輯我真正想做的是無限循環播放聲音,從viewdidload開始,在應用退出時,音樂應停止播放(而不是在后台播放)。 這是我正在嘗試開發的游戲

實際上,我正在使用的每種方法都會返回相同的錯誤:(日志摘錄)

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'

編輯結束

謝謝

這是播放添加到捆綁中的短聲音的非常簡單的方法:

NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"somesound" ofType:@"aif"];

SystemSoundID soundID;

AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);

AudioServicesPlaySystemSound (soundID);

這是有關“ 系統聲音服務參考”的更多文檔。

編輯 :由於您不想只播放簡短的聲音,這可能會更好:

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //infinite

[player play];

有關更多信息,請參見AVAudioPlayer類參考

根據您的錯誤,您到聲音文件的路徑無效(NSURL對於無效路徑返回nil)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM