如何在 Xcode 中制作一个全局停止 AVAudioPlayer 的按钮?
How to make a button in Xcode that globally stops AVAudioPlayer?
我正在尝试让 tableviewcell 在单击时停止应用程序中的所有声音。我知道如何使用 soundEffect.stop() soundEffect.currentTime = 0
停止声音,但我不知道如何将它应用到单元格,如果 StopSound 按钮位于另一个 viewController 上且具有不同的 [=14],这将不起作用=].如何制作一个全局停止 AVAudioPlayer 并将其应用于单元格的函数?
问题是玩家并不孤单。 .
要在另一个 ViewController 上停止 AVAudioPlayer,您可以使用 NotificationCenter。
示例...
第一次,在VC添加功能,需要停止AVAudioPlayer
@objc func stopAVonThisVC() {
AVaudioPlayer.stop()
}
其次,在此 VC 处添加 NotificationCenter 观察器,然后仅在 post 上点击按钮。
// 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
}
我正在尝试让 tableviewcell 在单击时停止应用程序中的所有声音。我知道如何使用 soundEffect.stop() soundEffect.currentTime = 0
停止声音,但我不知道如何将它应用到单元格,如果 StopSound 按钮位于另一个 viewController 上且具有不同的 [=14],这将不起作用=].如何制作一个全局停止 AVAudioPlayer 并将其应用于单元格的函数?
问题是玩家并不孤单。
要在另一个 ViewController 上停止 AVAudioPlayer,您可以使用 NotificationCenter。
示例...
第一次,在VC添加功能,需要停止AVAudioPlayer
@objc func stopAVonThisVC() {
AVaudioPlayer.stop()
}
其次,在此 VC 处添加 NotificationCenter 观察器,然后仅在 post 上点击按钮。
// 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
}