这是使用AVAudioPlayer的正确方法吗,我的代码看起来是否合适?

use*_*383 2 iphone

考虑到代码:

    soundFilePath = [[NSBundle mainBundle] pathForResource: @"Sound"    ofType: @"wav"];    
    fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];   
    avPlayerNextLevel = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL  error: nil];
    avPlayerNextLevel1.volume = volume ;
    [soundFilePath release];
    [fileURL release];
Run Code Online (Sandbox Code Playgroud)

然后播放声音

    if([avPlayerNextLevel prepareToPlay]){
        [avPlayerNextLevel play];
    }   
Run Code Online (Sandbox Code Playgroud)

我在游戏中多次这样做.有时在模拟器上,声音停止播放.有时我会用AvAudioPlayer检测到内存泄漏.

我的代码一切都好看吗?

小智 8

您需要释放您创建的AVAudioPlayer实例.由于上面的代码将委托设置为self,只需实现以下方法并在那里释放:

    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"Audio finished playing.");
    [player release];
}
Run Code Online (Sandbox Code Playgroud)