【问题标题】:Stop AVAudioplayer from single button从单个按钮停止 AVAudioplayer
【发布时间】:2023-04-05 07:06:01
【问题描述】:

当用户点击“完成”按钮时,我试图停止警报声。这是我现在使用的代码。当它提到使用相同的按钮时,我找不到任何解决方案。

@objc func runTimer() {

        if isTimerRunning {
            cafe.time -= 1

            if cafe.time <= 0 {
                timer.invalidate()
                let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
                alarmSound = try! AVAudioPlayer(contentsOf: url!)
                alarmSound.play()

                if alarmSound.isPlaying {
                    startButton.setTitle("Done", for: .normal)


                }
            }

@IBAction func startButtonPressed(_ sender: Any) {

        if !isTimerRunning {
            navigationItem.hidesBackButton = true
            isTimerRunning = true
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
            print("time")
            startButton.setTitle("Stop Brewing", for: .normal)
        } else {
            navigationItem.hidesBackButton = false
            isTimerRunning = false
            resetTimer()
            startButton.setTitle("Start Brewing", for: .normal)
        }
        if startButton.currentTitle == "Done"{
          alarmSound.stop()
        }else{
          alarmSound.play()
        }

    }

提前致谢!

【问题讨论】:

    标签: swift xcode uibutton avaudioplayer


    【解决方案1】:

    取一个变量来检查音频是否正在播放

    var playing = false
    

    在更改按钮文本时设置playing = true(完成)

    并在点击事件中应用下面的代码

    @IBAction func startButtonPressed(_ sender: Any) {
    
    if playing == true {
       alarmSound.stop()
    }else{
    
    alarmSound.play()
    
     }
    }
    

    【讨论】:

    • 它可以工作,然后对其进行投票,以便对其他人有所帮助
    • 一旦我获得 15 名声望我就会这样做:)
    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2018-09-14
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多