ios - 点击按钮时重复播放声音

标签 ios xcode swift avaudioplayer

我正在尝试为我的应用程序添加声音。我喜欢它,因为当我点击一个按钮时,它会播放快速的声音。但是,当快速重复点击按钮时,声音效果不佳(当我点击按钮 5 或 6 次时,它只播放 1 或 2 次)。这是我在按钮中的代码

player.play()

我在外面有这个

var player = AVAudioPlayer()
let audioPath = NSBundle.mainBundle().pathForResource("illuminati", ofType: "wav")

查看加载:

do {
        try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
    } catch {}

如何更好地反复播放声音?谢谢。

最佳答案

问题是您在上一个调用完成之前多次调用 play。您需要跟踪用户单击按钮的次数和播放歌曲的次数。

这是你可以做的:

  1. 在你的类中使用一个整数来跟踪按钮被点击的次数

    var numClicks = 0
    var buttonClickTime:NSDate? = nil // The last time when the button is clicked
    
    @IBAction func yourbuttonclickfunction() {
        numClicks++; 
        buttonClickTime = NSDate()
        player.play()
    } 
    
  2. 注册AVAudioPlayerDelegate的委托(delegate)

    do {
          try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
    
          // Add this 
          player.delegate = self
    } catch {}
    
  3. 在delegate函数中,当上一首歌曲播放结束时再次播放:

    optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
                         successfully flag: Bool)
    {
         if --numClicks > 0
         {
             let now = NSDate()
             let duration = now.timeIntervalSinceDate(buttonClickTime!)
    
             // If the button click was less than 0.5 seconds before
             if duration < 0.5 
             {
                 // Play the song again
                 player.play();
             } 
         }
    }
    

关于ios - 点击按钮时重复播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020266/

相关文章:

ios - 检查 UITableViewCell 是否完全可见的最佳方法

ios - NIDropDown iOS Obj-c - 未获取选定值

c - 链接 c 项目时体系结构 x86_64 的 undefined symbol

ios - UITableViewCell 中的 UIButton 默认点击动画

iphone - 是否有网站展示如何重新创建特定的 iOS UI 范例?

ios - 如何将用户与涉及 Apple 状态通知的自动续订订阅相关联?

iphone - 为什么 UITabBarController 中的 viewDidAppear 在 View 出现之前执行?

函数中的 Swift 3 枚举导致应用程序崩溃

ios - Swift 4 - 带选项卡栏和导航 Controller 的 3D Touch 快速操作

ios - 如何检查设备是否在 MDM 中注册