0

我有这种播放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];  
}

每次调用此方法时,我都会得到一个新字符串“声音”,然后每次此 AVAudioplayer“播放器”时都必须分配;我想在我停止或完成时释放它……有可能吗?

4

2 回答 2

2

试试下面的说明

你的ViewController.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];

谢谢..!

于 2012-04-20T08:41:12.623 回答
0

看看 AVAudioPlayerDelegate。

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

于 2012-04-20T08:39:20.653 回答