0
votes

I’m trying to play a sound using the AVAudioPlayer without success. I’ve tried it both in the iOS Simulator and on my iPhone. I don’t get any errors, but I also don’t hear a sound.

Here’s my code:

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"RiggerSound_Click" ofType: @"wav"];
    NSLog( @"Path is %@", soundFilePath );

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

    NSError *error;
    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &error];
    [fileURL release];

    if (newPlayer != nil)
    {
        if( ![newPlayer play] )
            NSLog( @"Error playing" );

        [newPlayer release];
    }
    else
        NSLog(@"Error creating audioPlayer: %@", [error localizedDescription]);

The soundFilePath is “/Users/myname/Library/Application Support/iPhone Simulator/6.1/Applications/E50059DD-B328-45C7-A5D5-C650F415B183/appname.app/RiggerSound_Click.wav”.

The “newPlayer” variable is not null and [newPlayer play] does not fail.

The file “RiggerSound_Click.wav” is shown in the Resources folder of my project. I can select it in the project, click the Play button, and hear the sound.

I’m stumped.

Thanks for your help.

2
Have you set up an AVAudioSession for your app?Patrick Goley
Releasing the player right away without keeping another reference will keep it from playingRob van der Veer

2 Answers

0
votes

Set the AVAudioPlayer's delegate before playing. For example,

newPlayer.delegate = self;

Also, make sure your delegate's class conforms to the AVAudioPlayerDelegate protocol:

MyClass : Superclass <AVAudioPlayerDelegate>
-1
votes

Just define the AVAudio Player as static

static AVAudioPlayer *newPlayer = Nil;
if(newPlayer == Nil)
{
     newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &error];
}

That's it