AVAudioPlayer:MP3文件无法在设备上播放,但适用于模拟器(iOS 6)

时间:2013-02-26 15:44:44

标签: iphone ios objective-c avaudioplayer

我正在使用下面的代码在iOS 6上播放带有AVAudioPlayer的MP3文件。该文件似乎正在播放,但设备上没有声音输出。 它可以在iOS模拟器中正常工作。

档案.h:

#import "UIKit/UIKit.h"
#import "AVFoundation/AVFoundation.h"

@interface ViewController : UIViewController <AVAudioPlayerDelegate>

@property (strong, nonatomic) AVAudioPlayer *player;

@end

档案.m:

#import "ViewController.h"

@implementation ViewController

@synthesize player;

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"beep_7" ofType:@"mp3"];
    NSLog(@"Audio path: %@", soundFilePath);

    NSError *error;
    player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFilePath] error:&error];

    if (error) {
        NSLog(@"Error in audioPlayer: %@",[error localizedDescription]);
    } 
    else {
        [player setDelegate:self];
        [player setNumberOfLoops:3]; //just to make sure it is playing my file several times
        player.volume = 1.0f;

        if([player prepareToPlay]) //It is always ready to play
            NSLog(@"It is ready to play");
        else
            NSLog(@"It is NOT ready to play ");

        if([player play]) //It is always playing
            NSLog(@"It should be playing");
        else
            NSLog(@"An error happened");
    }
}
@end

3 个答案:

答案 0 :(得分:5)

您发布的代码对我来说很好。

  • 您确定要在目标中加入beep_7.mp3吗?
  • 您确定文件名是否正确? iOS设备使用区分大小写的文件系统!
  • 您确定自己的设备没有静音吗?
  • 您确定该文件是有效的MP3文件吗?

答案 1 :(得分:2)

检查设备的静音模式是打开还是关闭? 我曾经遇到过和你一样的问题,在我改变了我的模式之后,所有人都解决了!

答案 2 :(得分:0)

您是否设置了AudioSessionCategory?

{
    NSError *setCategoryError = nil;
    BOOL success = [[AVAudioSession sharedInstance] setCategory: 
    avaudiosessioncategoryplayandrecorderror: &setCategoryError];
}