views:

274

answers:

2

I initialize an ivar AVAudioPlayer variable, play and the try to release its memory. After the release line, it doesn't set to 0x0. After the nil line it doesn't change to 0x0. Does AVAudioPlayer require something special to release its memory?

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource: @"mysound" ofType: @"aif" inDirectory:@"/"]] error: &err];
audioPlayer.numberOfLoops = 0;
audioPlayer.volume = .5;
[audioPlayer prepareToPlay];
[audioPlayer play];
[audioPlayer release];
audioPlayer = nil;
+2  A: 

Well,

AVAudioPLayer plays the audio files asynchronously. You should not release the player after you start playing, it may lead to some memory related error and your audio file may not play too.

You should release the player via avaudioplayerdelegate. For more details you can check this answer too.

Hope this helps.

Thanks,

Madhup

Madhup
I notice even when releasing and setting to nil in the delegate method, audioPlayerDidFinishPlaying, it doesn't set to 0x0.
4thSpace
+1  A: 
 - (IBAction) playaction {

        NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"songname" ofType:@"mp3"];
        NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
        self.soundFileURL = newURL;
        [newURL release];
        [[AVAudioSession sharedInstance] setDelegate: self];
        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];

    // Registers the audio route change listener callback function
    AudioSessionAddPropertyListener (
                                     kAudioSessionProperty_AudioRouteChange,
                                     audioRouteChangeListenerCallback,
                                     self
                                     );

    // Activates the audio session.

    NSError *activationError = nil;
    [[AVAudioSession sharedInstance] setActive: YES error: &activationError];

    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
    self.appSoundPlayer = newPlayer;
    [newPlayer release];
    [appSoundPlayer prepareToPlay];
    [appSoundPlayer setVolume: 1.0];
    [appSoundPlayer setDelegate: self];
    [appSoundPlayer play];

}

Here, appSoundPlayer is declared in the header file as

AVAudioPlayer *appSoundPlayer;

It is property declared and synthesized, also released at dealloc method as

[appSoundPlayer release];
Nithin
Thanks. How do I play sounds back to back? I have one after the other setup via method, similar to what you are doing above. However, only the second one plays.
4thSpace
how are you implementing that??? The best way is to use the method- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { if (flag) {//your mathod to play next one.}}
Nithin