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:
AVAudioSessionCategoryAmbient
: use this channel if the sound is not important for the functioning of the appAVAudioSessionCategoryMultiRoute
: use this channel if you are sending the sound to multiple output devices at the same timeAVAudioSessionCategoryPlayAndRecord
: use this channel for sound recording and playbackAVAudioSessionCategoryPlayback
: use this channel to play recorded music and other sounds that are important for the app's functioningAVAudioSessionCategoryRecord
: use this channel for sound recording; other sound is mutedAVAudioSessionCategorySoloAmbient
: the default channel to play sound
// 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
}
}
}