代码和调试: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!))
}
}
}
1条答案
按热度按时间vaj7vani1#
谢谢@jnpdx!下面是我的工作,我使用了一个计时器(withTimeInterval =音频的持续时间)来更新Bool的isAudioPlaying