.isPlaying ошибки с помощью кнопки Pause / Play в SwiftUI - PullRequest
0 голосов
/ 21 января 2020

У меня проблема с использованием .isplaying в swiftui. Каждый раз у меня возникает ошибка с кнопкой, которую я создал для управления функцией паузы / воспроизведения. По сути, кнопка должна воспроизводить песню, если ничего не воспроизводится, и останавливать то, что воспроизводится, если что-то воспроизводилось ранее. Я не уверен, из-за чего может возникнуть эта ошибка, и, если нужно разместить больше кода, я могу сделать это без проблем.

Вот код и ошибка.

Button(action:  {

                            let sound = Bundle.main.path(forResource: "vcem983", ofType: "mp3")

                            if self.audioPlayer!.isPlaying == true  {

                                self.audioPlayer!.pause()

                                self.audioPlayer! = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
                                self.audioPlayer!.prepareToPlay()
                                self.audioPlayer!.play()

                            }   else    {

                                self.audioPlayer!.play()

                            }

                            // Continuously fetching current audio time
                            // Used background to avoid affecting main thread
                            DispatchQueue.global(qos: .background).async   {

                                while true  {

                                    let screenWidth = UIScreen.main.bounds.width - 20
                                    let currenttime = self.audioPlayer!.currentTime / self.audioPlayer!.duration
                                    let timeForLabel = CGFloat(currenttime) * screenWidth
                                    self.time = timeForLabel
                                    print(currenttime)
                                }
                            }
                        })  {
                            Image(systemName: "waveform")
                                .font(.caption)
                            Text("EMOTION 98.3")
                                .font(.caption)
                                .fontWeight(.semibold)
                                .multilineTextAlignment(.center)
                            }
                                .frame(minWidth: 0, maxWidth: 300)
                                .padding()
                                .background(Color(.secondarySystemBackground))
                                .cornerRadius(35)

Code + error

1 Ответ

1 голос
/ 21 января 2020

Вы используете принудительное развертывание - это приводит к созданию sh. Попробуйте использовать мой код и вы можете обновить logi c. К сожалению, в swiftUI нет состояния viewDidLoad(), и я переместил инициализацию audioPlayer в onAppear.

struct ContentView: View {

    @State var audioPlayer: AVAudioPlayer!

    var body: some View {
        Button(action: {

            if self.audioPlayer.isPlaying {
                self.audioPlayer.pause()
            } else {
                self.audioPlayer.play()
            }

            // Continuously fetching current audio time
            // Used background to avoid affecting main thread
            DispatchQueue.global(qos: .background).async   {
                while true  {
                    let screenWidth = UIScreen.main.bounds.width - 20
                    let currenttime = self.audioPlayer.currentTime / self.audioPlayer.duration
                    let timeForLabel = CGFloat(currenttime) * screenWidth
                    print(currenttime)
                }
            }
        })  {
            Image(systemName: "waveform")
                .font(.caption)
            Text("EMOTION 98.3")
                .font(.caption)
                .fontWeight(.semibold)
                .multilineTextAlignment(.center)
        }.onAppear {
            guard let sound = Bundle.main.url(forResource: "vcem983", withExtension: "mp3") else { return }
            do {
                self.audioPlayer = try AVAudioPlayer(contentsOf: sound)
                self.audioPlayer.prepareToPlay()
            } catch let parseError {
                print("error parse: \(parseError)")
            }
        }
                .frame(minWidth: 0, maxWidth: 300)
                .padding()
                .background(Color(.secondarySystemBackground))
                .cornerRadius(35)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...