Create an Audio Player in SwiftUI
Written by Team Kodeco
SwiftUI, combined with AVFoundation, allows you to create a versatile audio player in your app easily.
First, you need to import AVFoundation
, Apple’s framework for manipulating audio and video content, which provides the AVAudioPlayer
class for audio playback.
For this example, you’ll create a AudioPlayerViewModel
to handle your audio player logic.
Note: If you want to try out the examples, you can download an archive of all the assets used in this section here.
import AVFoundation
class AudioPlayerViewModel: ObservableObject {
var audioPlayer: AVAudioPlayer?
@Published var isPlaying = false
init() {
if let sound = Bundle.main.path(forResource: "PocketCyclopsLvl1", ofType: "mp3") {
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
} catch {
print("AVAudioPlayer could not be instantiated.")
}
} else {
print("Audio file could not be found.")
}
}
func playOrPause() {
guard let player = audioPlayer else { return }
if player.isPlaying {
player.pause()
isPlaying = false
} else {
player.play()
isPlaying = true
}
}
}
The AudioPlayerViewModel
class serves as the bridge between your SwiftUI view and the AVAudioPlayer
instance. It handles the initialization of AVAudioPlayer
and manages the playback state. The class also logs appropriate error messages if the audio file is missing or if the audio player cannot be instantiated.
Next, you’ll create the SwiftUI view that interacts with your AudioPlayerViewModel
.
struct ContentView: View {
@StateObject var audioPlayerViewModel = AudioPlayerViewModel()
var body: some View {
VStack {
Button(action: {
audioPlayerViewModel.playOrPause()
}) {
Image(systemName: audioPlayerViewModel.isPlaying ? "pause.circle" : "play.circle")
.resizable()
.frame(width: 64, height: 64)
}
}
}
}
Here’s what your preview should look like:
In the ContentView
, you instantiate AudioPlayerViewModel
as a @StateObject
, ensuring that the instance persists for the lifetime of ContentView
. You provide a button which, when tapped, invokes the playOrPause
method on your view model, thus controlling the audio playback. The image within the button dynamically changes to reflect the current playback state — a play icon when the audio is paused, or a pause icon when the audio is playing.
And that’s it! You’ve successfully built a simple audio player using SwiftUI and AVFoundation.