不能使用两个“audioPlayerDidFinishPlaying”

时间:2011-08-04 20:43:09

标签: xcode memory-management xcode4 avaudioplayer

你能告诉我如何解决这个问题吗?我想在完成播放时释放两个不同的AVAudioPlayer,但是要分开。

这是我的代码:

.h文件

@interface ViewController : UIViewController <AVAudioPlayerDelegate>
{
     NSString          *path;
}

- (IBAction)Short:(id)sender;
- (IBAction)BeatLong:(id)sender;

.m文件

AVAudioPlayer   *media;
AVAudioPlayer   *media2;

- (IBAction)Short:(id)sender
{
    path = [[NSBundle mainBundle] pathForResource:@"Short" ofType:@"wav"];
    media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    [media setDelegate:self];
    [media play];
}

- (IBAction)Beat:(id)sender
{
    path = [[NSBundle mainBundle] pathForResource:@"Beat" ofType:@"mp3"];
    media2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    [media2 setDelegate:self];
    [media2 play];
}

.m

(在新标签页中打开图片以便更好地查看^^,)

1 个答案:

答案 0 :(得分:2)

不,这种语言是非法的。

您必须根据AVAudioPlayer *指针区分不同的玩家 随信息提交。

如果您只想发布它,请写下

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)aPlayer successfully:(BOOL)flag
{ 
    [aPlayer release]; 
}

你已经完成并且非法,因为你没有aPlayer。

但更好的解决方案是检测您拥有的音频播放器并将其发布。

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)aPlayer successfully:(BOOL)flag
{ 
    if ( aPlayer == self.media )
        [self.media release];
    else if ( aPlayer == self.media2 ) 
        [self.media2 release];
    // other players cannot be released, since we don't know anything about their owner.
}