Question:
In Swift code, apart from using an
NSTimer
, how can I get animations to start at exact points during playback of a music file played usingAVFoundation
?
背景
我有一个使用 AVFoundation
播放音乐文件的方法(如下)。我还有 UIView 动画,我想在播放音乐文件期间从准确的点开始。
实现此目的的一种方法是使用 NSTimer
,但这有可能会不同步或不够准确。
有没有一种方法可以让我利用 AVFoundation
访问音乐文件的耗时(计时器),以便在音乐播放过程中的某些点到达时,动画开始?
是否有 AVFoundation
触发的事件/通知提供自音乐文件开始播放以来经过的持续时间流?
例如
在 0:52.50(52 秒 1/2),调用 startAnimation1()
,在 1:20.75(1 分 20 秒 3/4),调用 startAnimation2( )
,等等?
switch musicPlayingTimeElapsed {
case 0:52.50:
startAnimation1()
case 1:20.75:
startAnimation2()
default:
()
}
使用 AVFoundation
播放音乐
import AVFoundation
var myMusic : AVAudioPlayer?
func playMusic() {
if let musicFile = self.setupAudioPlayerWithFile("fileName", type:"mp3") {
self.myMusic = musicFile
}
myMusic?.play()
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
var audioPlayer:AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("AVAudioPlayer not available")
}
return audioPlayer
}
最佳答案
如果您使用 AVPlayer
而不是 AVAudioPlayer
,您可以使用(TBH 有点尴尬)addBoundaryTimeObserverForTimes
方法:
let times = [
NSValue(CMTime:CMTimeMake(...)),
NSValue(CMTime:CMTimeMake(...)),
NSValue(CMTime:CMTimeMake(...)),
// etc
];
var observer: AnyObject? = nil // instance variable
self.observer = self.player.addBoundaryTimeObserverForTimes(times, queue: nil) {
switch self.player.currentTime() {
case 0:52.50:
startAnimation1()
case 1:20.75:
startAnimation2()
default:
break
}
}
// call this to stop observer
self.player.removeTimeObserver(self.observer)
关于ios - 如何在播放音乐文件期间让动画在精确点工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560111/