Image generated with ChatGPT

Member-only story

Playing music in SwiftUI application

Nicola De Filippo
3 min readDec 23, 2023

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

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Nicola De Filippo
Nicola De Filippo

Written by Nicola De Filippo

Software Engineer and Entrepreneur

No responses yet

Write a response