如何在iPhone中播放声音时执行操作?

Cri*_*ris 5 iphone avaudioplayer

我使用AVAudioPlayer在我的iPhone应用程序中播放MP3; 我需要在某些时间执行某些操作(比如30秒,1分钟); 有没有办法根据mp3播放时间调用回调函数?

Amy*_*all 8

我相信最好的解决方案是在NSTimer你开始AVAudioPlayer比赛时开始.您可以将计时器设置为每半秒左右触发一次.然后,每次计时器触发时,请查看currentTime音频播放器上的属性.

为了按特定时间间隔执行某些操作,我建议您为上次调用计时器回调时的回放时间保留一个实例变量.然后,如果您已经通过了上次回调和此之间的关键点,请执行您的操作.

所以,在伪代码中,定时器回调:

  1. 获取currentTime您的AVAudioPlayer
  2. 检查是否currentTime大于criticalPoint
  3. 如果是,请检查是否lastCurrentTime小于criticalPoint
  4. 如果也是,请采取行动.
  5. 设置lastCurrentTimecurrentTime


mrw*_*ker 5

如果您能够使用AVPlayer而不是AVAudioPlayer,则可以设置边界或周期时间观察器:

// File URL or URL of a media library item
AVPlayer *player = [[AVPlayer alloc] initWithURL:url];        

CMTime time = CMTimeMakeWithSeconds(30.0, 600);
NSArray *times = [NSArray arrayWithObject:[NSValue valueWithCMTime:time]];

id playerObserver = [player addBoundaryTimeObserverForTimes:times queue:NULL usingBlock:^{
    NSLog(@"Playback time is 30 seconds");            
}];

[player play];

// remove the observer when you're done with the player:
[player removeTimeObserver:playerObserver];
Run Code Online (Sandbox Code Playgroud)

AVPlayer文档:http: //developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVPlayer_Class/Reference/Reference.html


Jam*_*ter 1

我发现这个链接描述了一个属性,它似乎表明您可以获得当前的播放时间。

如果正在播放声音,则 currentTime 是当前播放位置的偏移量,以秒为单位从声音开始算起。如果声音未播放,则 currentTime 是调用 play 方法时播放开始位置的偏移量,以从声音开始算起的秒数为单位。

通过设置此属性,您可以寻找声音文件中的特定点或实现音频快进和快退功能。

要检查时间并执行操作,您只需查询即可:

if (avAudioPlayerObject.currentTime == 30.0) //You may need a more broad check. Double may not be able to exactly represent 30.0s
{
    //Do Something
}
Run Code Online (Sandbox Code Playgroud)