2012-08-26 157 views

回答

0

顯然這個結果是相當混亂,但我找到了一個解決方案。我正在運行XCode 4.4.1。

這裏是爲我工作的步驟:

  1. 將MP3文件從取景到XCode項目 - >支持文件。確保複製文件。假設文件名是sound.mp3。
  2. 將AVFoundation框架添加到您的項目中。
  3. 進口< AVFoundation/AVFoundation.h>

  4. @property(強)AVAudioPlayer *聲音播放;
  5. 使用以下代碼初始化播放器並播放mp3: NSURL * chemin = [NSURL fileURLWithPath:[NSString stringWithFormat:@「%@/sound.mp3」,[[NSBundle mainBundle] resourcePath]]]; NSError *錯誤; self.soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:chemin error:& error]; [self.soundPlayer play];

現在,在這一點上,我在此所說明的異常:AVFoundation iOS 5 總之這意味着有可能是不應該在設備上發生的模擬器中的錯誤。在我的情況下,我打開了所有異常,這阻止了我的代碼執行。你應該做的是刪除拋出所有異常的選項。

此外,在我的情況下,它只有3-5秒纔會播放聲音,所以請耐心等待,直到您沒有立即聽到聲音。第一次播放後,它會立即播放。

3

我知道播放MP3文件的最簡單方法是使用AVAudioPlayer類。基本上,只是做(跳過錯誤檢查,檢測完成設置委託等):

NSURL* soundUrl = [[NSBundle mainBundle] URLForResource:@"soundFile" withExtension:@"mp3"]; 
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&err]; 
[player play]; 
+0

+1可能是最簡單的播放音頻的方式,我只是做了一些小小的調整,使這些iOS新手更容易理解。 –

+0

我嘗試過但它不起作用,它引發了一個異常,我無法準確地看到它到達程序集。 – kernix

+0

@kernix您是否導入了AVFoundation框架? –

1

首先添加AVFoundation框架到項目[轉至目標>項目右鍵單擊>構建階段>鏈接二進制與圖書館>點擊on +> select AVFoundation> Add]

// get file path 
NSString *soundPath = [[NSBundle mainBundle] pathForResource: fileNameToPlay ofType:@"mp3"]; 

// allocate and refer to file 
AVAudioPlayer *player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: soundPath] error: NULL]; 

// set delegate 
player. delegate = self; 

// play 
[player play]; 
相關問題