Poipoi
Poipoi

Reputation: 13

How to play two sounds continuously in one button in SwiftUI

screenshot

I need to create one button which can run two sounds continuously. My present code, the button can run SoundA and SoundB at the same time. But I want user to click on one button which can play SoundA. Then SoundA has finished, and then play SoundB automatically(right after SoundA has ended). Thank you for your helping.

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)
        }
    }
    
}
        

I also have tried, but it doesn't work.

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

Upvotes: 0

Views: 301

Answers (1)

Jan Podmolík
Jan Podmolík

Reputation: 121

Get the length of your first sound.

let duration = self.audioPlayer1.duration

Play your first sound..

self.audioPlayer1.play()

Insert length that you get into asyncAfter DispatchQueue and play second sound.

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

You can also hardcode seconds of your first sound or increase pause by adding more seconds. Hope that help..

Upvotes: 1

Related Questions