问题描述
我使用AVAudioPlayer在iPhone应用程序中播放MP3;我需要在某些时间(例如30秒1分钟)执行一些操作;有没有一种方法可以根据mp3播放时间来调用回调函数?
I play a MP3 in my iPhone app using AVAudioPlayer; i need to perform some operations at certain times (say 30th seconds, 1 minute); is there a way to invoke callback functions based on mp3 playing time?
推荐答案
我相信最好的解决方案是在开始播放AVAudioPlayer
时启动NSTimer
.您可以将计时器设置为每半秒左右触发一次.然后,每次您的计时器启动时,请查看音频播放器上的currentTime
属性.
I believe the best solution is to start an NSTimer
as you start the AVAudioPlayer
playing. You could set the timer to fire every half second or so. Then each time your timer fires, look at the currentTime
property on your audio player.
为了以一定的间隔执行某项操作,建议您从上次调用计时器回调开始,保留一个实例变量作为回放时间.然后,如果您已在上次回调和此回调之间传递了关键点,请执行操作.
In order to do something at certain intervals, I'd suggest you kept an instance variable for the playback time from last time your timer callback was called. Then if you had passed the critical point between last callback and this, do your action.
因此,使用伪代码,计时器回调:
So, in pseudocode, the timer callback:
- 获取AVAudioPlayer的
currentTime
- 检查
currentTime
是否大于criticalPoint
- 如果是,请检查
lastCurrentTime
是否小于criticalPoint
- 如果也是,请执行操作.
- 将
lastCurrentTime
设置为currentTime
- Get the
currentTime
of your AVAudioPlayer - Check to see if
currentTime
is greater thancriticalPoint
- If yes, check to see if
lastCurrentTime
is less thancriticalPoint
- If yes to that too, do your action.
- Set
lastCurrentTime
tocurrentTime
这篇关于在iPhone中播放声音时如何执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!