2012-07-21 31 views
0

我成功地播放了一個類文本的MP3文件。但是,當我將功能移出到單獨的類時,它會失敗。IOS - 播放mp3失敗時移動到一個單獨的類

這裏的工作代碼:

頁眉:

#import <AVFoundation/AVFoundation.h> 

@interface QuestionController : UIViewController 
<UITableViewDataSource, UITableViewDelegate, UISplitViewControllerDelegate> 
{ 
    AVAudioPlayer *audioPlayer; 

} 

工作代碼:

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/A.mp3", [[NSBundle mainBundle] resourcePath]]]; 

    NSError *error; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = 0; 

    if (audioPlayer == nil) 
     NSLog(@"audio errror: %@",[error description]);    
    else 
     [audioPlayer play]; 

這裏的新類:

頁眉:

#import <Foundation/Foundation.h> 
#import <AVFoundation/AVFoundation.h> 


    @interface AudioPlayer : NSObject { 

    } 

    - (void *) playAudioFile:(NSString *) mp3File; 

    @end 

實現:

#import "AudioPlayer.h" 

    @implementation AudioPlayer 

    - (void *) playAudioFile:(NSString *) mp3File { 

     NSLog(@"mp3file to play: %@", mp3File); 

     NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@", mp3File, [[NSBundle mainBundle] resourcePath]]]; 

     NSError *error; 

     AVAudioPlayer *audioPlayer; 
     audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
     audioPlayer.numberOfLoops = 0; 

     if (audioPlayer == nil) { 
      NSLog(@"audio errror: %@",[error description]); 
     } 
     else { 
      [audioPlayer play]; 
     } 
     [audioPlayer release]; 

     return 0; 
    } 

    @end 

下面是調用代碼:

AudioPlayer *audioPlayer = [[AudioPlayer alloc] init]; 

    [audioPlayer playAudioFile:@"/A.mp3"]; 

然而,當它在單獨的類運行時,它不會成功創建播放器轉移到「音頻播放器= =零」分支

下面是輸出:

012-07-21 07:14:54.480 MyQuiz[6655:207] mp3file to play: /A.mp3 
2012-07-21 07:15:40.827 MyQuiz[6655:207] audio errror: Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)" 

網址是「file://localhost/A.mp3」

任何想法我做錯了什麼?當我重構分離方法時,我總是遇到麻煩。這很令人沮喪。

回答

1

你在URL錯誤,這條線

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@", mp3File, [[NSBundle mainBundle] resourcePath]]]; 

改成這樣:

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], mp3File]]; 
1

彈出的第一件事是您在播放後立即釋放音頻播放器,而在「工作」類中這不會發生。

解決此問題的好設計是在Singleton類中實例化音頻播放器一次。這個班級應負責在整個應用程序中播放音頻,並應管理來自所有班級的任何請求。這樣你就知道你在正確地管理內存,並且AVFoundation框架只能在一個地方使用。

另外,讓你需要的路徑,使用方法:

NSURL *url = [NSURL fileURLWithPath:[[NSString stringWithFormat:@"%@", mp3File] stringByAppendingPathComponent:[[NSBundle mainBundle] resourcePath]]]; 
+0

我想你是對的,釋放導致了一個問題。但另一個爲NSUrl提出的解決方案是解決了無效字符串格式問題的解決方案。 – 2012-07-21 15:30:41

+0

沒有問題。無論如何,我建議使用stringByAppendingPathComponent,它更適合您的需求,並且是一個更通用的方法。 – Stavash 2012-07-21 15:33:15