7492

Strange behaviour with AVAudioPlayer on the iPhone

Question:

I'm attempting to play a sound using AVAudioPlayer. Should be simple, but I'm seeing some odd results.

Code:

NSString *path = [[NSBundle mainBundle] pathForResource:@"pop" ofType:@"wav"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *sound = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [sound play]; [sound release];

What I'm seeing is that the sound doesn't play when using the app normally.

It plays <strong>only</strong> if I step through the code using the debugger, it doesn't play when executing any other way...

I'm not creating any new threads or run loops within my app, so this should all be running on the main thread, at least [NSThread isMainThread] returns true.

Anyone got any ideas as to what is going on here?

Answer1:

AVAudioPlayer's play method is asynchronous, so you're starting to play the sound and then immediately releasing it! That's why it works when you step through it in the debugger -- you're giving it time to play before killing it. What you want to do is implement AVAudioPlayerDelegate's - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag method and release the audio player there, after the sound is done playing.

Answer2:

papajohn is right you should do it like this

Have a class level variable of audio player like

AVAudioPlayer *classLevelPlayer;

synthesize this object. and in the call to player method

-(void)playTheSong{ if(classLevelPlayer!=nil){ [classLevelPlayer stop]; [self setClassLevelPlayer:nil]; } NSString *path = [[NSBundle mainBundle] pathForResource:@"pop" ofType:@"wav"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *sound = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; if(sound){ [self setClassLevelPlayer:sound]; [classLevelPlayer play]; } [sound release]; }

and in

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { [self setClassLevelPlayer:nil]; }

Hope this helps.

Recommend

  • Rivets, Backbone.View and Backbone.Collection
  • Standard way for writing a debug mode in C++
  • Debug PHP in Atom While Using Vagrant
  • Add a div to replace Video after Video Plays Through
  • Edit assembly language code in Visual Studio while stepping through each statement
  • CUDA Debugging - VS on windows workstation, GPUs on Linux server?
  • Converting raw frames into webm live stream
  • Error while re-opening sound file in python
  • RegistryKey.GetSubKeyNames returns names that are not in that subkey!
  • C# Excel interop - how to test if interop object is still working and performing a task?
  • Why does java tzupdater add leap seconds?
  • Question about instantiating object
  • Debugging VB6 Code From Visual Studio 2010
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Diff between two dataframes in pandas
  • NSScanner Loop Question
  • Limiting recursion to certain level - Duplicate rows
  • Row Count Is Returning the incorrect number using RaptureXML
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • Debugging ASP.NET on a built-in web server suddenly stops
  • req.body is undefined - nodejs
  • Obtain ObjectIdHex value from mgo query
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • Trying to switch camera back to front but getting exception
  • Symfony2: How to get request parameter
  • Eraser for UIBezierPath
  • Akka Routing: Reply's send to router ends up as dead letters
  • Compare two NSDates in iPhone
  • Is there a mandatory requirement to switch app.yaml?
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • Acquiring multiple attributes from .xml file in c#
  • Hits per day in Google Big Query
  • -fvisibility=hidden not passed by compiler for Debug builds
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Linking SubReports Without LinkChild/LinkMaster
  • How can I remove ASP.NET Designer.cs files?
  • Bitwise OR returns boolean when one of operands is nil
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • java string with new operator and a literal