2012-10-22 23 views
0

我想實現播放聲音和/或音樂的播放器。我有這兩種方法:AVAudioPlayer無法使用(NSString *)文件名

-(void)playSound:(int)soundIndex 
{ 
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[SoundFxFilenameArray objectAtIndex:soundIndex] ofType:@"mp3"]]; 

    if(FxPlayer) 
    { 
    [FxPlayer release]; 
    FxPlayer = nil; 
    } 

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil]; 

    FxPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; 
    [FxPlayer play]; 
} 

-(void)playMusic:(NSString *)filename 
{ 
    NSURL *url = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:filename ofType:@"mp3"]]; 

    if(MusicPlayer) 
    { 
    [MusicPlayer release]; 
    MusicPlayer = nil; 
    } 

    MusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; 
    [MusicPlayer play]; 
} 

現在,[[SoundPlayer sharedManager] playSound:FXIndex_Default]工作得很好。當我嘗試播放音樂時,[[SoundPlayer sharedManager] playMusic:@"music_file_name_here"只是沒有做任何事情。請注意,聲音文件和音樂文件的格式都是相同的(mp3)。

此外,「sharedInstance」是因爲我實現了這個音頻播放器的單身模式。

任何指示或想法是什麼在我的代碼錯誤,以便我可以播放聲音,但不是音樂?

回答

0

使用fileURLWithPath而不是URLWithStringplayMusic

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:filename ofType:@"mp3"]]; 

URLWithString需要一個完整的URL,例如 「文件://path/to/file.mp3」 作爲參數,fileURLWithPath預計只是一個文件路徑。

+0

哦,男人,正是這樣!感謝您的解釋! :) – sebkkom

+0

@sebkomianos:'URLWithString'適用於各種URL,「http:」,「file:」等,因此它必須知道URL方案。 'fileURLWithPath'是文件URL的特殊方法。 –