Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer not working on iOS7

I have tried all the different options found here, even using NSData to load the the audio files. I have tried mp3, m4a, caf files but nothing is working.

No error messages, nothing.

This is a new app using XCODE 5, iOS7.

This is what I'm using

- (void)playOnce:(NSString *)aSound
{


    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
    [audioSession setActive:YES error:nil];

    // Gets the file system path to the sound to play.
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:aSound ofType:@"m4a"];

    // Converts the sound's file path to an NSURL object
    NSURL *soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL: soundURL error:nil];


    [newAudio prepareToPlay];

    // set it up and play
    [newAudio setNumberOfLoops:0];
    [newAudio setVolume: 1];
    [newAudio setDelegate: self];
    [newAudio play];

}

Any help is greatly appreciated. I've been stuck with these for too long now.

In advance, thank you.

like image 399
Elkucho Avatar asked Nov 30 '22 20:11

Elkucho


2 Answers

You need to declare your AVAudioPlayer as a strong referenced @property in view controller like below

@property (strong, nonatomic)  AVAudioPlayer * newAudio;

If you declare AVAudioPlayer in a method, it will be released right after the method got executed, there is not enough time to make a sound .

like image 193
Pride Chung Avatar answered Dec 20 '22 03:12

Pride Chung


I tried like this and I was able to play Audio files in iOS 7

- (void)viewDidLoad {
  [super viewDidLoad];

  NSURL* url = [[NSBundle mainBundle] URLForResource:@"DR" withExtension:@"mp3"];
  NSAssert(url, @"URL is valid."); 
  NSError* error = nil;
  self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
  if(!self.player) {
    NSLog(@"Error creating player: %@", error);
  }
  self.player.delegate = self;
  [self.player prepareToPlay];
}

- (IBAction)playAction:(id)sender {
   [self.player play];
}
like image 34
MahboobiOSDeveloper Avatar answered Dec 20 '22 03:12

MahboobiOSDeveloper