2010-01-08 100 views
1

我初始化一個ivar AVAudioPlayer變量,播放和嘗試釋放它的內存。釋放行後,它不會設置爲0x0。在零線之後,它不會更改爲0x0。 AVAudioPlayer是否需要特殊的東西來釋放它的內存?AVAudioPlayer不釋放內存

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

好,

AVAudioPLayer異步播放音頻文件。開始播放後,您不應釋放播放器,否則可能會導致與內存有關的錯誤,並且您的音頻文件可能無法播放。

你應該通過avaudioplayerdelegate釋放玩家。欲瞭解更多詳情,你可以檢查這個answer too

希望這會有所幫助。

謝謝,

Madhup

+0

我注意到,即使在委託方法audioPlayerDidFinishPlaying中釋放並設置爲nil時,它也不會設置爲0x0。 – 4thSpace 2010-01-08 04:41:42

1
- (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]; 

} 

這裏,appSoundPlayer被聲明在頭文件作爲

AVAudioPlayer *appSoundPlayer; 

據屬性聲明併合成,也在dealloc方法釋放爲

[appSoundPlayer release]; 
+0

謝謝。我該如何播放聲音?我有一個接着一個通過方法設置,類似於你在做什麼。但是,只有第二個玩。 – 4thSpace 2010-01-08 05:12:01

+0

你怎麼實現?最好的辦法是使用方法 - (空)audioPlayerDidFinishPlaying:成功(AVAudioPlayer *)播放器:(BOOL)標誌{ \t如果(標誌)\t \t {// 您馬託玩下一個。 } } – Nithin 2010-01-08 05:32:24

+0

Uhhh夥計,你不是指'[self.appSoundPlayer發佈];'?如果你聲明它爲'@property(nonatomic,retain)AVAudioPlayer * appSoundPlayer;'你一定需要使用點語法來訪問它('self.appSoundPlayer') – 2012-12-10 21:56:54