SwiftUI:audioPlayer开始播放后,当可选的Bool = true时,if/else中的视图不起作用

smdncfj3  于 2022-10-31  发布在  Swift
关注(0)|答案(1)|浏览(108)

代码和调试:https://i.stack.imgur.com/PxsWn.jpg
我正在尝试使用.isPlaying来检查我的audioPlayer当前是否正在播放。我所期望的是在音频未播放时看到“播放”,如果音频正在播放则看到“暂停”。
我尝试过:在我的模拟器中,我点击了“是否正在播放音频”来验证audioPlayer?.isPlaying最初是否为false,然后点击“播放”来播放音频。之后,我再次点击了“是否正在播放音频”,audioPlayer?.isPlaying = true。
即使audioPlayer?.isPlaying = true,“暂停”按钮也没有出现。有人知道为什么吗?

import SwiftUI
import AVKit

struct aNote: View {
    @State private var audioPlayer: AVAudioPlayer!
    var body: some View {
        VStack {
            if audioPlayer?.isPlaying ?? false {
                Button(action: {self.audioPlayer.pause()}, label: {Text("PAUSE")})
            } else {Button(action: {self.audioPlayer.currentTime = 0; self.audioPlayer.play()}, label: {Text("PLAY")})
            }
            Button(action: {print(audioPlayer?.isPlaying)}, label: {Text("Is the audio playing")})
        }
        .onAppear {
            let sound = Bundle.main.path(forResource: "A#", ofType: "mp3")
            self.audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
        }
    }
}
vaj7vani

vaj7vani1#

谢谢@jnpdx!下面是我的工作,我使用了一个计时器(withTimeInterval =音频的持续时间)来更新Bool的isAudioPlaying

class NewAudioControl: ObservableObject {
    var audioPlayer: AVAudioPlayer!
    @Published var isAudioPlaying = false

    func playSound(filename: String, duration: Double) {
        let sound = Bundle.main.path(forResource: filename, ofType: "mp3")
        self.audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
        self.audioPlayer.play()
        isAudioPlaying = audioPlayer.isPlaying
        Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { [self]_ in isAudioPlaying = audioPlayer.isPlaying}
    }

    func pauseSound() {
        self.audioPlayer.pause()
        self.audioPlayer.currentTime = 0
        isAudioPlaying = audioPlayer.isPlaying
    }
}

struct noteA: View {
    @ObservedObject var newAudioControl = NewAudioControl()
    var body: some View {
        if newAudioControl.isAudioPlaying {Button(action: {newAudioControl.pauseSound()}, label: {ButtonView(buttonColour: "noteText", noteColour: "noteButton", note: "A")})
        } else {Button(action: {newAudioControl.playSound(filename: "A", duration: 28.0)}, label: {ButtonView(buttonColour: "noteButton", noteColour: "noteText", note: "A")})
        }
    }
}

相关问题