2015-08-25 46 views
1

我有一个带有animateWithDuration和setAnimationRepeatCount()动画的脉冲矩形。animateWithDuration播放声音不重复

我试图在动画块中添加声音效果的女巫是同步“点击”。但音效只播放一次。我无法在任何地方找到任何提示。

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) 
} 
+0

动画重复吗? – ricky3350

+0

声音是否播放?音频片段有多长? – dudeman

+0

动画重复。声音只播放一次。音频剪辑只是一个短的点击:长度0.36秒,格式MP3 –

回答

2

提供UIViewAnimationOptions.Repeat选项确实不是导致动画块被重复调用。该动画在CoreAnimation级别上重复。如果你在动画块中放置一个断点,你会发现它只执行一次。

如果您希望动画在声音旁边的循环中执行,请创建一个重复的NSTimer并从那里调用动画/声音。请记住,定时器将保留目标,所以不要忘记使定时器无效以防止保留周期。

编辑:新增实施以下

首先,我们需要创建一个定时器,假设我们有一个名为timer实例变量。这可以在视图的viewDidLoad:init方法中完成。一旦初始化,我们就安排用运行循环执行,否则它不会重复发射。

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) 
} 
+0

好的,我明白了,这就是问题所在。我对Swift很陌生。你能提供一个关于如何实现一个同步调用动画和声音的NSTimer的例子吗?提前致谢。 –

+0

请检查更新的答案与实施。 – dbart

+0

鼓舞人心的解决方案,在mainRunLoop上添加定时器。这解决了我的问题。非常感谢你!!! –

0

没有看到音频播放器实现的一些事情,我能想到的包括:

  • 音频文件太长,也许对最终的沉默它所以它没有播放文件的第一部分,其中有声音

  • 需要将音频文件设置为fil的开头Ë每次(它可能只是在玩其他的3倍,导致没有音频输出文件的末尾)

  • 动画正在发生迅速和音频没有足够的时间来缓冲

希望这些建议可以帮助你缩小问题范围,但是如果没有看到玩家的执行情况,就很难说出实际的问题。