如何在SwiftUI中一键连续播放两种声音

How to play two sounds continuously in one button in SwiftUI

screenshot

我需要创建一个可以连续 运行 两种声音的按钮。 我现在的代码,按钮可以同时运行 SoundA和SoundB。 但我希望用户单击一个可以播放 SoundA 的按钮。 然后SoundA结束,然后自动播放SoundB(SoundA结束后)。 感谢您的帮助。

import SwiftUI
import AVKit

struct ContentView: View {
    @State var audioPlayer1: AVAudioPlayer!
    @State var audioPlayer2: AVAudioPlayer!
    var body: some View {
     
          
            Button(action: {
                
                let sound1 = Bundle.main.path(forResource: "soundA", ofType: "mp3")
                let sound2 = Bundle.main.path(forResource: "soundB", ofType: "mp3")
                
                self.audioPlayer1 = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound1!))
                self.audioPlayer2 = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound2!))
                
                self.audioPlayer1.play()
                self.audioPlayer2.play()
            }){ Text("Play sound")
                .frame(width:300, height: 100)
                .background(Color.yellow)
        }
    }
    
}
        

我也试过了,还是不行

self.audioPlayer1.play()
self.audioPlayer1.stop()
self.audioPlayer2.play()

获取第一个声音的长度。

let duration = self.audioPlayer1.duration

播放你的第一个声音..

self.audioPlayer1.play()

将您进入 asyncAfter DispatchQueue 的长度插入并播放第二个声音。

DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
self.audioPlayer2.play()
            }

您还可以对第一个声音的秒数进行硬编码,或者通过增加秒数来增加停顿。希望有所帮助..