2010-04-12 75 views
2

我在播放filesAVAudioPlayer時遇到問題。當我嘗試播放某個m4a時,它工作正常。它也適用於我嘗試的MP3。然而,無論每次嘗試播放它們的順序如何,它每次都會失敗(15步,由Radiohead)。音頻只是不play,雖然視圖加載和一切發生併發正確發生。代碼如下。我得到了「玩家加載」。另外兩首歌曲的日誌輸出,但不是15步。我知道file path是正確的(我有它在應用程序中輸出日誌,它是正確的)。有任何想法嗎?AVAudioPlayer只用一些文件初始化

NSData *musicData = [NSData dataWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]]]; 

NSLog([[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]); 
if(musicData) 
{ 
    NSLog(@"File found."); 
} 

self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:nil]; 

if(self.songView.player) 
{ 
    NSLog(@"Player loaded."); 
} 

[self.songView.player play]; 
NSLog(@"You should be hearing something now."); 

回答

0
NSData *musicData = [NSData dataWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]]]; 

這裏,是musicDatanil的問題呢?

另外:

self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:nil]; 

你不應該爲採取NSError對象的方法傳遞nil。如果你正確地使用它,它可能會讓你的問題更加明朗:

NSError* error = nil; 
self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:&error]; 
if (error) 
{ 
    NSLog(@"Error with initWithData: %@", [error localizedDescription]); 
} 
+0

感謝NSError的提示......我是新來的Objective-C,並不知道如何正確使用它。我會給你一個鏡頭。 不幸的是,musicData在問題情況中不是零。我記錄了進入它的URL,它是正確的。如果我仍然有問題,我會嘗試更多內容並重新發布。 再次感謝! – Brendan 2010-04-14 00:32:32

1

對不起,這麼晚進入派對。只是想發佈一個提示,以便將來對任何人提及這一點將是有用的。

shaggy frog的答案進行了小修改。正確的用法是:

NSError *anError = nil; 
anAVAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:someURL] error:&anError]; 
if (!anAVAudioPlayer) { 
    NSLog(@"localizedDescription : %@", [anError localizedDescription]); 
} 
+0

有同樣的問題 - 這是一個間歇性問題,我將表單數據切換到網址,它也工作 – yeahdixon 2013-12-21 04:04:12