我创建了一个按钮,该按钮可在播放另一个剪辑时使在后台运行的音频静音,但是,如果我按“取消”按钮以停止播放该音频文件并播放另一个,则它将继续运行上一个按钮上关联的代码。有些按钮的音频文件比其他按钮长,所以我试图找到一种取消代码background.volume = 2
的方法,但是我没有运气,有人能找出解决方法或取消该方法的方法吗?退出先前的代码请求?
@IBAction func AudioSet1(_ sender: Any) {
NSObject.cancelPreviousPerformRequests(withTarget: DispatchQueue.main)
if ResetAction.isEnabled == true {
let AudioSet1 = URL(fileURLWithPath: Bundle.main.path(forResource: "AudioSet1", ofType: "mp3")!)
do {
audioPlayer = try
AVAudioPlayer(contentsOf: AudioSet1)
audioPlayer.prepareToPlay()
} catch {
print("File load error #5")
}
audioPlayer.play()
audioPlayer.volume = 2
background.volume = 0
self.ResetAction.isEnabled = false
if audioPlayer.isPlaying{
do{
DispatchQueue.main.asyncAfter(deadline: .now() + 16.5) {
self.background.volume = 2
self.ResetAction.isEnabled = true
}}}}
}
@IBAction func AudioSet2(_ sender: Any) {
NSObject.cancelPreviousPerformRequests(withTarget: DispatchQueue.main.suspend())
if ResetAction.isEnabled == true {
let AudioSet2 = URL(fileURLWithPath: Bundle.main.path(forResource: "AudioSet2", ofType: "mp3")!)
do {
audioPlayer = try
AVAudioPlayer(contentsOf: AudioSet2)
audioPlayer.prepareToPlay()
} catch {
print("File load error #3")
}
audioPlayer.play()
audioPlayer.volume = 2
self.ResetAction.isEnabled = false
if audioPlayer.isPlaying{
self.background.volume = 0
do {
DispatchQueue.main.asyncAfter(deadline: .now() + 27){
self.background.volume = 2
self.ResetAction.isEnabled = true
}}}}
}
那是音频按钮,这是清除按钮,我想要在其中取消代码的asyncAfter部分:
`@IBAction func Reset(_ sender: Any) {
if background.volume == Float(0){
NSObject.cancelPreviousPerformRequests(withTarget: DispatchQueue.main.self)
}
let AudioRender = URL(fileURLWithPath: Bundle.main.path(forResource: "", ofType: "mp3")!)
do {
audioPlayer = try
AVAudioPlayer(contentsOf: AudioRender)
audioPlayer.prepareToPlay()
} catch {
print("File load error #1")
}
audioPlayer.play()
audioPlayer.volume = 0
background.volume = 2
self.ResetAction.isEnabled = true
}`
谢谢