【问题标题】:How to rapidly press a button to generate sound on Xcode?如何快速按下按钮在 Xcode 上生成声音?
【发布时间】:2017-06-07 02:51:39
【问题描述】:

这是我的以下 Xcode 项目代码。当我按下“play()”时,会发出短促的鼓声。问题是,当我连续多次点击自定义视图时,我希望连续出现快速的鼓声。但是,声音会在完整剪辑(2 秒)完成后出现,留下大量死区。我尝试了很多不同的方法,但我做不到。

@IBOutlet weak var tabla: TablaHead!

var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!)
var tablaAudioPlayer = AVAudioPlayer()


override func viewDidLoad() {
    super.viewDidLoad()
    tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL)
}

@IBAction func tapped(_ sender: UITapGestureRecognizer) {
    if sender.state == .ended {
        playNoise()
    }
}

public func playNoise() {
    if (tablaAudioPlayer.isPlaying) {
        tablaAudioPlayer.stop()
        tablaAudioPlayer.play()
    } else {
        tablaAudioPlayer.play()
    }
}

【问题讨论】:

    标签: ios swift xcode audio


    【解决方案1】:

    试试这样的

    @IBOutlet weak var tabla: TablaHead!
    
    var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!)
    var tablaAudioPlayer = AVAudioPlayer()
    var tapsCount = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL)
    }
    
    @IBAction func tapped(_ sender: UITapGestureRecognizer) {
        tapsCount += 1
        if sender.state == .ended && tapsCount == 1 {
            playNoise()
        }
    }
    
    public func playNoise() {
        tapsCount -= 1
        tablaAudioPlayer.play()
        if tapsCount > 0 {
            playNoise()
        }
    }
    

    【讨论】:

    • 不走运。我认为问题在于我不完全了解 AVAudioPlayer。感谢您的尝试!
    猜你喜欢
    • 2011-03-08
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多