AVAudioPlayer 没有播放我试过的 Mp3 文件但是没有运气

AVAudioPlayer Not playing Mp3 File I tried But no luck

您好,我正在使用以下代码播放我的本地 mp3 文件。但没有错误出现。但是 mp3 没有播放。

AVAudioPlayer  *audioPlayer ;
NSString *sound_file;
if ((sound_file = [[NSBundle mainBundle] pathForResource:@"mpthreetest" ofType:@"mp3"])){

    NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    audioPlayer.delegate = self;


    [audioPlayer prepareToPlay];
    [audioPlayer play];

}

检查以下步骤。

  1. 你的AppDelegate.m

    #import <AVFoundation/AVAudioSession.h>`<AVFoundation/AVAudioSession.h>
    
  2. 你的application:didFinishLaunchingWithOptions:方法

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        self.window.backgroundColor = [UIColor whiteColor];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    }
    
  3. 在你的ViewController.h

    @property (nonatomic,retain) AVAudioPlayer  *audioPlayer ;
    
  4. 在你的ViewController.m

    @synthesize audioPlayer;
    

然后

NSString *sound_file;
if ((sound_file = [[NSBundle mainBundle] pathForResource:@"mpthreetest" ofType:@"mp3"])){

    NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    audioPlayer.delegate = self;

    [audioPlayer prepareToPlay];
    [audioPlayer play];    
}

你的错误是没有设置属性.