简体   繁体   中英

AVAudioPlayer: Simple sound not playing

I'm trying to figure out why sounds aren't playing in my app, so I created what I think is as simple an implementation as possible:

  NSError *error;
   NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"canary-trills" ofType:@"wav"];
  NSLog(@"string=%@", soundFilePath);
  NSURL *url = [[NSURL alloc] initFileURLWithPath:soundFilePath];
  NSLog(@"URL=%@", url);
  AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc]
                            initWithContentsOfURL:url error:&error];
  [avPlayer prepareToPlay];
  BOOL success = [avPlayer play];
  NSLog(@"The sound %@ play", success ? @"did" : @"didn't");

Per the console, it looks like it finds the resource, creates the URL correctly. Even the play call indicates success. However, no sound play in the simulator nor the device.

AVAudioPlayer wasn't being retained & was going out of scope.

Adding: @property (strong, nonatomic) AVAudioPlayer *audioPlayer;

to the class & using that member solved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM