Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

Wrap an AVAudioPlayer and play a sound in a SwiftUI view.
Wrap an AVAudioPlayer and play a sound in a SwiftUI view.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.