如何在全球停止Avaudioplayer的XCode中制作一个按钮



我正在尝试在单击应用程序中停止所有声音。我知道如何使用soundEffect.stop() soundEffect.currentTime = 0停止声音,但是我不知道如何将其应用于单元格,如果停止按钮在另一个带有不同类别的ViewController上,则无效。我如何制作全球范围停止Avaudioplayer并将其应用于单元格的函数?

问题是玩家并不孤单。尝试一下。

要在另一个ViewController上停止Avaudioplayer,您可以使用NotificationCenter。

示例...

第一次,在VC上添加功能,您需要停止Avaudioplayer。

@objc func stopAVonThisVC() {
    AVaudioPlayer.stop()
}

第二,在此VC上添加NotificationCenter观察者,然后仅发布点击按钮。

    // At VC, where you need to stop AVAudioPlayer.
NotificationCenter.default.addObserver(self, selector:
    #selector(stopAVonThisVC), name: NSNotification.Name("Stop at VC1"), object: nil)
    // At VC2
NotificationCenter.default.post(name: NSNotification.Name("Stop at VC1"), object: nil)

对不起,英语不好。

为您的项目创建一个BaseViewController,然后从那里子类子类,

在BaseViewController中定义AVAudioPlayer并从任何子类中调用soundEffect.stop() soundEffect.currentTime = 0,它应该解决问题。

示例:

    class BaseViewController: UIViewController {
    var audioPayer: AVAudioPlayer!
     }

    class ViewControllerA: BaseViewController { 
    //start or stop audio player
    }
    class ViewControllerB: BaseViewController {
    //start or stop audio player
    }

相关内容

最新更新