我有一个带有animateWithDuration和setAnimationRepeatCount()
的脉冲矩形动画。
我正试图在动画块中添加同步"点击"的声音效果。但是音效只播放一次。我在任何地方都找不到任何提示。
UIView.animateWithDuration(0.5,
delay: 0,
options: UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.Repeat,
animations: {
UIView.setAnimationRepeatCount(4)
self.audioPlayer.play()
self.img_MotronomLight.alpha = 0.1
}, completion: nil)
音效应该播放四次,但是没有。
音频实现://global:
var metronomClickSample = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("metronomeClick", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVAudioPlayer(contentsOfURL: metronomClickSample, error: nil)
audioPlayer.prepareToPlay()
....
}
@IBAction func act_toggleStartTapped(sender: AnyObject) {
....
UIView.animateWithDuration(....
animations: {
UIView.setAnimationRepeatCount(4)
self.audioPlayer.play()
self.img_MotronomLight.alpha = 0.1
}, completion: nil)
}
提供UIViewAnimationOptions.Repeat
选项是否NOT导致动画块被反复调用。动画在CoreAnimation
级别上重复。如果你在动画块中放置一个断点,你会注意到它只执行一次。
如果您希望动画与声音一起在循环中执行,请创建一个重复的NSTimer
并从那里调用动画/声音。请记住,计时器将保留目标,所以不要忘记使计时器失效,以防止保留循环。
EDIT:
首先,我们需要创建计时器,假设我们有一个名为timer
的实例变量。这可以在视图的viewDidLoad:
或init
方法中完成。初始化后,使用run循环调度执行,否则不会重复触发。
self.timesFired = 0
self.timer = NSTimer(timeInterval: 0.5, target: self, selector:"timerDidFire:", userInfo: nil, repeats: true)
if let timer = self.timer {
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}
以下是计时器每隔一段时间(在本例中为0.5秒)触发的方法。在这里,您可以运行动画和音频播放。注意,UIViewAnimationOptions.Repeat
选项已被删除,因为计时器现在负责处理重复的动画和音频。如果您只让计时器触发特定的次数,您可以添加一个实例变量来跟踪触发的次数,并在计数超过阈值时使计时器失效。
func timerDidFire(timer: NSTimer) {
/*
* If limited number of repeats is required
* and assuming there's an instance variable
* called `timesFired`
*/
if self.timesFired > 5 {
if let timer = self.timer {
timer.invalidate()
}
self.timer = nil
return
}
++self.timesFired
self.audioPlayer.play()
var options = UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.CurveEaseOut;
UIView.animateWithDuration(0.5, delay: 0, options: options, animations: {
self.img_MotronomLight.alpha = 0.1
}, completion: nil)
}
在没有看到音频播放器的实现的情况下,我能想到的一些事情包括:
-
音频文件太长,可能在它的末尾设置了静音,所以它不会播放文件中有声音的第一部分
-
音频文件每次都需要设置为文件的开头(它可能只是播放文件的结尾,其他3次导致没有音频输出)
-
动画发生得太快,音频没有时间缓冲
希望这些建议能帮助你缩小问题范围,但如果没有看到播放器的执行情况,就很难说出真正的问题是什么。