IOS:AVAudioPlayer管理内存

时间:2012-04-20 08:22:58

标签: ios xcode avaudioplayer

我有这种播放mp3的方法:

- (void) playSound:(NSString*)sound{

    NSString *path = [NSString stringWithFormat:@"%@/%@",
                      [[NSBundle mainBundle] resourcePath],
                      sound];
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:nil];
    [player prepareToPlay]; 
    [player play];  
}

每当我调用这个方法时,我会得到一个新的字符串“sound”,然后我必须每次都为这个AVAudioplayer“播放器”分配;我希望在我停止或完成时释放它...是否可能?

2 个答案:

答案 0 :(得分:2)

尝试以下说明

yourViewController.h

 @interface yourViewController : UIViewController <AVAudioPlayerDelegate>

yourViewController.m文件,用于添加功能

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
 //play finished
}

在代码

下面声明AVAudioPlayer对象
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
                                                                fileURLWithPath:[[NSBundle mainBundle] 
                                                                                 pathForResource:@"audio" ofType:@"mp3"]] error:NULL]; 

    audioPlayer.delegate = self;
    audioPlayer.currentTime=0.0f;
    [audioPlayer prepareToPlay];
    [audioPlayer play];

谢谢..!

答案 1 :(得分:0)

看看AVAudioPlayerDelegate。

它有方法audioPlayerDidFinishPlaying:successfully:和audioPlayerDecodeErrorDidOccur:error:应该让你做你想做的事。