AVAudioPlayer does not work on iOS7

I tried all the various options found here, even using NSData to download audio files. I tried mp3, m4a, caf files, but nothing works.

No error messages, nothing.

This is a new application using XCODE 5, iOS7.

This is what I use

- (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 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 appreciated. I have been stuck with them for too long.

Thank you in advance.

+4
source share
2 answers

You need to declare your AVAudioPlayer as a strong @property link controller, as shown below

@property (strong, nonatomic)  AVAudioPlayer * newAudio;

If you declare AVAudioPlayer in a method, it will be released immediately after the method is executed, there is no time for the sound to be missing.

+17
source

, 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];
}
+2

All Articles