2014-10-09 121 views
1

我不能为我的生活弄清楚为什么当我的声音做打我无法检测。我可以让它为视频工作没问题。我一直在寻找过去的两个小时,而且我遇到的解决方案似乎都没有效果。AVPlayerItemDidPlayToEndTimeNotification音频播放完毕后,不叫

声音正常播放。我只需要知道它什么时候结束。

.H

@interface soundController : UIViewController <AVAudioPlayerDelegate> { 

    AVAudioPlayer *audioPlayer; 

} 

- (IBAction) soundButtonClicked; 
- (void) soundDidStop:(NSNotification *)notification; 

的.m

- (IBAction) soundButtonClicked { 

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/my_sound.mp3", [[NSBundle mainBundle] resourcePath]]]; 
    NSError *error; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = 0; 


    [[NSNotificationCenter defaultCenter] addObserver:self 
          selector:@selector(soundDidStop:) 
          name:AVPlayerItemDidPlayToEndTimeNotification 
          object:audioPlayer]; 
    [audioPlayer play]; 

} 


- (void) soundDidStop:(NSNotification *)notification { 

    UIAlertView *alert = [[UIAlertView alloc] 
          initWithTitle:@"" 
          message:@"sound stopped" 
          delegate:nil 
          cancelButtonTitle:@"OK" 
          otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 


} 

任何了解是极大的赞赏。谢谢!

回答

1

AVPlayerItemDidPlayToEndTimeNotification`可供AVPlayerItem的通知,这是不是你使用的是什么在你的代码在那里。

您使用AVAudioPlayer,一个完全不同的对象有一个完全不同的接口。

而在你的情况,你可以使用AVAudioPlayerDelegate协议。您想要捕获的代表方法是audioPlayerDidFinishPlaying:successfully:

+0

嘿,感谢您的快速回复。我确实尝试过,但是我收到警告“'AVAudioPlayer'可能不会响应'currentItem'”。无论如何我试图运行,看看它是否会起作用,但不幸的是现在我得到了一个SIGABRT。 :\ – 2014-10-09 03:34:59

+0

啊,我只是意识到你使用AVAudioPlayer而不是AVPlayer,这是通知实际使用的内容。但更好的是,使用AVAudioPlayer,您可以使用可用的委托方法。 – 2014-10-09 04:16:06

+0

谢谢!这就是诀窍!我想它很明显,我不知道我在做什么。 :P你是一个拯救生命的人! – 2014-10-09 04:41:54