2013-10-06 46 views
1

我嘗試了一切,我可以找到嘗試讓我的應用程序播放一個MP3。我有幾個2-3秒的MP3播放聲音效果,但我試圖播放15s MP3沒有任何運氣。播放15秒mp3 ios

NSError *error; 
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: @"test" withExtension: @"mp3"] error:&error]; 
    if (error) { 
     NSLog(@"Error creating audio player: %@", [error userInfo]); 
    } else { 
     if([audioPlayer play] == FALSE) { 
      NSLog(@"Fail %@", error); 
     } 
    } 
    NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 15.0 target: self 
                 selector: @selector(stopMusic) userInfo: nil repeats: NO]; 

我懷疑計時器與它有什麼關係,但認爲我會包括它以防萬一。基本上我的錯誤檢查沒有被觸發。它「應該」正確播放,但沒有聲音出現,並且沒有顯示錯誤。

我已經嘗試了一些其他的事情來嘗試並得到這個工作,我已經嘗試了沒有計時器。我找不到一個體面的指南。我不需要一個完整的媒體播放器,只需要一些UIScreenViewController的背景音樂。

我也嘗試了下面的代碼,它適用於短MP3,不適用於我想播放的更長的MP3。

NSString *path = [[NSBundle mainBundle] pathForResource:@"bgmusic" ofType:@"mp3"]; 
NSURL *pathURL = [NSURL fileURLWithPath : path]; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &audioEffect); 
AudioServicesPlaySystemSound(audioEffect); 

請幫忙,我花了數小時試圖對此進行排序。看來蘋果每次發佈操作系統時都會重新調整音頻。

+0

您的播放器是否認爲它在播放?在if塊之後調用並記錄'[audioPlayer playing]'。也許與mp3文件有關?你的代碼看起來很適合我。 –

+0

它打印真實,所以它認爲它正在播放。 – FaddishWorm

回答

2

我爲你做了一些測試:結果是音樂文件在Xcode 5中默認沒有添加到目標中。因此URLForResource:error:可能會返回nil

嘗試從您的項目中刪除MP3。然後再添加它,這一次化妝舒爾將其添加到您的目標:

Xcode Screenshot

的另一件事是:好像你正在定義一個方法裏面AVAudioPlayer。您通常會爲您的音頻播放器設置一個@property,否則它的使用時間僅限於該方法 - 並且在您達到該方法結束後音樂停止播放。

+0

我已經複製到目標。這是AVAudioPlayer的方法 - 哇不能相信我錯過了一個謝謝! – FaddishWorm