2016-08-23 177 views
0

當我運行應用程序時,當應用程序播放我的MP3文件時,我聽不到任何聲音:「d.mp3」。 此文件在iTunes中可以播放。AVAudioPlayer不會播放MP3文件

我將AVFoundation.framework添加到項目中。 添加文件「d.mp3」到項目。

添加到瀏覽器:

#import <UIKit/UIKit.h> 
#import "AVFoundation/AVAudioPlayer.h" 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    // Play an MP3 file: 
    printf("\n Play an MP3 file"); 
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
             pathForResource:@"d" 
             ofType:@"mp3"]]; 
    printf("\n url = %x", (int)url); 
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] 
            initWithContentsOfURL:url 
            error:nil]; 
    printf("\n audioPlayer = %x", (int)audioPlayer); 
    [audioPlayer play]; 
} 

輸出日誌:

Play an MP3 file 
url = 3ee78eb0 
audioPlayer = 3ee77810 
+0

也許嘗試通過一個非空參數傳遞給'錯誤:'參數,看看它試圖告訴你問題是什麼? –

+0

我不相信AVAudioPlayers會保留自己,這意味着玩家可能會立即被釋放。你能把它存儲在一個強大的實例變量上,看看它是否有效? – Msencenb

+0

請勿使用'printf'和'%x'。使用'NSLog'和'%@'。這會給你提供更多有用的信息,指針地址! – jcaron

回答

1

非ARC

你必須在播放期間留住它,因爲它不保留本身。一旦它被解除分配,它將立即停止播放。

ARC

您需要在類中保存AVAudioPlayer實例。並停止播放後釋放它。例如,

#import <AVFoundation/AVFoundation.h> 

@interface YourController() <AVAudioPlayerDelegate> { 
AVAudioPlayer *_yourPlayer; // strong reference 
} 
@end 

@implementation YourController 

- (IBAction)playAudio:(id)sender 
{ 
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"d" withExtension:@"mp3"]; 
    _yourPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL]; 
    _yourPlayer.delegate = self; 
    [_yourPlayer play]; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
    if (player == _yourPlayer) { 
     _yourPlayer = nil; 
    } 
} 

@end 

希望這有助於

+0

它只有在將playAudio的內容移動到viewDidLoad後纔有效。 –

+0

好的,意味着代碼就是你要找的東西? – gurmandeep