ios - 如何在播放音乐文件期间让动画在精确点工作?

标签 ios swift animation avfoundation avaudioplayer

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 using AVFoundation?


背景

我有一个使用 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/

相关文章:

WPF 动画 - 为什么 "By"不能有负值?

javascript - 处理 Prop 更改时的 SVG 动画的最佳方法是什么?

ios - 弹出回 View Controller 时 UIButton 文本不更新

swift - 如何隐藏/显示某些 UIView 的 UI 导航栏

ios - Swift:将开始和结束日期格式化为单个字符串

swift - 让物体从屏幕边缘反弹?

ios - OptionSet 中是否可以有超过 64 个成员?

python - Matplotlib basemap 多个形状动画异常: 'list' object has no attribute 'set_animated'

ios - Xcode 5.1 :error for architecture x86_64 Facebook ios sdk

ios - OpenGL ES - 降低纹理质量和纹理大小