Audio control - SwiftUI

In iOS apps written in SwiftUI you should always provide a pause or stop button for media. When using AVPlayer, you should use play and pause methods.

You should also make sure that audio is played through the correct channel. Use AVAudioSession in combination with AVAudioSessionCategory to achieve this.

The following channels are available:

// Set audio channel
try AVAudioSession.sharedInstance().setCategory(
    .playback, 
    mode: .default, 
    options: []
)

// Provide media controls
@State private var player = AVPlayer()
@State private var isPlaying = false

var body: some View {
    Button(isPlaying ? "Pause" : "Play") {
        if player.timeControlStatus == .playing {
            player.pause()
            isPlaying = false
        } else {
            player.play()
            isPlaying = true
        }
    }
}