2014-02-21 28 views

回答

1

嘗試這樣的:

@import AVFoundation; 

... 

AVAudioPlayer * backgroundMusicPlayer; 
NSError *error; 
NSURL * backgroundMusicURL = [[NSBundle mainBundle] URLForResource:@"song" withExtension:@"m4a"]; 
backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error]; 
backgroundMusicPlayer.numberOfLoops = -1; //-1 = infinite loop 
[backgroundMusicPlayer prepareToPlay]; 
[backgroundMusicPlayer play]; 

,並停止簡單

[backgroundMusicPlayer stop]; 

注:我不使用SKAction播放背景音樂,因爲當你想

你不能阻止它
+1

我用這一點,但沒有任何聲音傳出來 –

+0

你也許可以想到的爲什麼會出現沒有聲音?我也聽不到任何... – LinusGeffarth

1

您可以使用AVAudioPlayer達到此目的:

在您的.h:

#import <AVFoundation/AVFoundation.h> 

,並添加以下到interface

AVAudioPlayer *player; 

在.M,音頻誓言網址初始化播放器:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
              pathForResource:@"bg_music" 
              ofType:@"mp3"]]; 
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; 
player.numberOfLoops = -1; 

,當你需要播放音頻,你可以調用:

[player play]; 

注意: 「numberOfLoops」是在達到結尾時聲音將返回到開頭的次數。

  • 零值意味着只播放一次聲音。
  • 值爲1會導致播放聲音兩次,依此類推...
  • 任何負數將無限循環直到停止。

保持編碼................ :)

+0

由於未捕獲異常「NSInvalidArgumentException」而終止應用程序,原因:'*** - [NSURL initFileURLWithPath:]:nil字符串參數' - 你知道爲什麼會發生這種情況嗎? – LinusGeffarth

+0

@LiGe:表示在指定的路徑中沒有文件/甚至是錯誤的路徑。檢查資源的路徑,區分大小寫及其擴展名。 –

+0

那麼路徑是正確的。我反而使用了未解答的適當的線,它解決了我的問題,但我聽不到任何音樂......:/ – LinusGeffarth