立即关闭声音

Toggle sound off straight away

我创建了一个切换按钮来打开 off/on 音乐。这个问题是我必须关闭应用程序才能生效。

这是我用来开始音乐的:

.onAppear(perform: {self.musicM.playSoundBand(sound: "Band", type: "wav")})

这是我的切换按钮:

 Toggle(isOn: self.$musicM.mOn) {
                    ZStack {
                        Image("Button")
                            .renderingMode(.original)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .rotationEffect(Angle(degrees: 180))
                            .padding([.leading, .trailing], 40);
                        Text("Music")
                            .padding(.all, 20)
                            .padding([.leading, .trailing], 40)
                            .font(.largeTitle)
                            .foregroundColor(.black)
                    }
                    Spacer()
                }.onTapGesture(perform: {if self.musicM.mOn == false { self.musicM.pauseMusicBand(); self.soundEffectsM.playSound(sound: "GunCock", type: "wav")}})

我尝试了各种变体并利用 .stop() 但仍然无法正常工作。如果有帮助,我的声音管理器 class 还有:

class musicModel: ObservableObject {
    var audioPlayerBand:AVAudioPlayer?
    @Published var mOn: Bool = UserDefaults.standard.bool(forKey: "mOn") {
        didSet {
            UserDefaults.standard.set(self.mOn, forKey: "mOn")
        }
    }
    func pauseMusicBand() {
        UserDefaults.standard.set(false, forKey: "mOn"); audioPlayerBand?.pause()
    }
    func setVolume(volume: Float) {
        audioPlayerBand?.volume = volume
    }
    func playSoundBand(sound: String, type: String) {
        if let path = Bundle.main.path(forResource: sound, ofType: type) {
            do {
                audioPlayerBand = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                audioPlayerBand?.numberOfLoops =  -1
                audioPlayerBand?.play()
            } catch {
                print("ERROR: Could not find sound file!")
            }; if self.mOn == false { pauseMusicBand() }
        }
    }
}

此测试代码展示了如何立即关闭声音:

import SwiftUI
import Foundation
import AVFoundation

struct ContentView: View {

@ObservedObject var musicM = musicModel()

var body: some View {
        Toggle(isOn: Binding<Bool>(
            get: { self.musicM.mOn },
            set: { self.musicM.mOn = [=10=]; self.doMusic() })) {
            ZStack {
                Image("Button")
                    .renderingMode(.original)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .rotationEffect(Angle(degrees: 180))
                    .padding([.leading, .trailing], 40);
                Text("Music")
                    .padding(.all, 20)
                    .padding([.leading, .trailing], 40)
                    .font(.largeTitle)
                    .foregroundColor(.black)
            }
            Spacer()
    }.onAppear(perform: self.startBackgroundMusic)
}

func startBackgroundMusic() {
    // if you want to always start the background music, then toggle should be set
//        self.musicM.mOn = true
//        self.musicM.playSoundBand(sound: "Band", type: "wav")

    // if you want to play the background music only if the user has set it last time
    if self.musicM.mOn {
        self.musicM.playSoundBand(sound: "Band", type: "wav")
    }
}

func doMusic() {
    if self.musicM.mOn {
        self.musicM.playSoundBand(sound: "Band", type: "wav")
    } else {
        self.musicM.audioPlayerBand?.pause()
     //   self.soundEffectsM.playSound(sound: "GunCock", type: "wav")
    }
}
}

class musicModel: ObservableObject {
var audioPlayerBand: AVAudioPlayer?

@Published var mOn: Bool = UserDefaults.standard.bool(forKey: "mOn") {
    didSet {
        UserDefaults.standard.set(self.mOn, forKey: "mOn")
    }
}
func pauseMusicBand() {
    UserDefaults.standard.set(false, forKey: "mOn")
    audioPlayerBand?.pause()
}
func setVolume(volume: Float) {
    audioPlayerBand?.volume = volume
}
func playSoundBand(sound: String, type: String) {
    if let path = Bundle.main.path(forResource: sound, ofType: type) {
        do {
            audioPlayerBand = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            audioPlayerBand?.numberOfLoops =  -1
            audioPlayerBand?.play()
        } catch {
            print("ERROR: Could not find sound file!")
        }
    }
}
}