
In this short post, we’ll learn how to add the play function to our SwiftUI application. To test this functionality, we will add a Christmas song to our previous project (timer-and-shape-in-swiftui).
First, we need to create a player. We’ll do this by using the new Observable class annotation, which also works in the latest iOS 17. Some might wonder why I’m focusing on the latest features. The goal of my post is to update current iOS developers on the latest advancements and to help new developers, who usually start by using the most recent tools, create code effectively.
So, let’s take a look at the player:
import AVFoundation
@Observable
class AudioPlayerViewModel {
var audioPlayer: AVAudioPlayer?
var isPlaying = false
init() {
if let sound = Bundle.main.path(forResource: "silent", ofType: "mp3") {
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
} catch {
print("AVAudioPlayer can't be instantiated.")
}
} else {
print("Audio file not found.")
}
}
func playOrPause() {
guard let player = audioPlayer else { return }
if player.isPlaying {
player.pause()
isPlaying = false
} else {
player.play()
isPlaying = true
}
}
}