rubrin
rubrin

Reputation: 99

AVAudioPlayer: MP3 file not playing on device, but works in Simulator (iOS 6)

I'm using the code below to play a MP3 file with AVAudioPlayer on iOS 6. The file seems to be playing, but there is no sound output on the device. It works fine in the iOS Simulator though.

File .h:

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

@interface ViewController : UIViewController <AVAudioPlayerDelegate>

@property (strong, nonatomic) AVAudioPlayer *player;

@end

File .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

Upvotes: 4

Views: 2541

Answers (3)

Susu
Susu

Reputation: 1

Did you set AudioSessionCategory?

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

Upvotes: 0

Ryan
Ryan

Reputation: 21

check your device's silent mode is on or off? I once got the same problem as yours,after i changed my slient mode off,all solved!

Upvotes: 2

Andreas Ley
Andreas Ley

Reputation: 9335

The code you've posted works fine for me.

  • Are you sure you're including the beep_7.mp3 in your target?
  • Are you sure the filename is correct? iOS devices use a case-sensitive filesystem!
  • Are you sure your device isn't muted?
  • Are you sure the file is a valid, working MP3 file?

Upvotes: 5

Related Questions