Make Your iOS App Stand Out with This Powerful Audio Player

Make Your iOS App Stand Out with This Powerful Audio Player

In this article, we will be discussing a Swift snippet that allows users to play, pause, and stop a guided meditation audio file, as well as track the progress of the audio with a progress bar. We will take a closer look at how the code works and explore some ideas on how to customize it to fit your own needs. This code is suitable for Swift developers looking to incorporate audio playback functionality into their iOS apps.

import SwiftUI
import AVFoundation
import UIKit

struct guidedMeditationView: View {
    @State private var audioPlayer: AVAudioPlayer?
    @State private var isPlaying: Bool = false
    @State private var storedTime: TimeInterval = 0
    @State private var progress: Double = 0.0
    @State private var timer: Timer?

    var body: some View {
        VStack{
            HStack {
                Button(action: { self.play() }) {
                    Image(systemName: "play.square.fill")
                        .font(.system(size: 50.0))
                }

                Button(action: { self.pause() }) {
                    Image(systemName: "pause.rectangle.fill")
                        .font(.system(size: 50.0))
                }

                Button(action: { self.stop() }) {
                    Image(systemName: "xmark.square.fill")
                        .font(.system(size: 50.0))
                }
            }
            ProgressView("Progress:", value: progress, total: 1.0)
                .id(progress)
                .frame(width: 200, height: 20)

        }
    }

    func play() {
        guard let fileURL = Bundle.main.url(forResource: "Guided Meditation Compassion", withExtension: "m4a") else {
            print("Error finding audio file")
            return
        }

        do {
            if audioPlayer == nil {
                audioPlayer = try AVAudioPlayer(contentsOf: fileURL)
            }
            audioPlayer?.currentTime = storedTime
            audioPlayer?.play()
            isPlaying = true
            timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
                self.updateProgress()
            }
        } catch {
            print("Error playing audio: \(error)")
        }
    }

    func pause() {
        audioPlayer?.pause()
        isPlaying = false
        storedTime = audioPlayer?.currentTime ?? 0
        timer?.invalidate()
    }

    func stop() {
        audioPlayer?.stop()
        audioPlayer = nil
        isPlaying = false
        storedTime = 0
        timer?.invalidate()
    }

    func updateProgress() {
        guard let audioPlayer = audioPlayer else { return }
        progress = audioPlayer.currentTime / audioPlayer.duration
        print("update progress")
    }
}

The code begins by importing the necessary libraries: SwiftUI, AVFoundation, and UIKit. AVFoundation is an Apple framework that provides classes for playing and interacting with audio and video files, while UIKit is a framework that provides classes for creating iOS applications.

Next, we have the guidedMeditationView struct, which conforms to the View protocol. This struct has several @State variables: audioPlayer, isPlaying, storedTime, progress, and timer. audioPlayer is an instance of AVAudioPlayer that is used to play the audio file, isPlaying is a Bool that indicates whether the audio is currently playing, storedTime is a TimeInterval that stores the current time of the audio player when it is paused, progress is a Double that represents the progress of the audio player, and timer is an instance of Timer that is used to update the progress variable.

The body of the guidedMeditationView struct is a VStack that contains a HStack of buttons for playing, pausing, and stopping the audio, and a ProgressView that displays the progress of the audio player. The play, pause, and stop functions are responsible for controlling the audio player. The play function retrieves the URL of the audio file and creates an instance of AVAudioPlayer with it. It then sets the current time of the audio player to the stored time, plays the audio, and sets the isPlaying variable to true. It also creates an instance of Timer to update the progress variable every second. The pause function simply pauses the audio player and stores the current time, while the stop function stops the audio player and resets all the variables.

One of the key features of this audio player is the progress bar, which allows the user to track the progress of the audio as it plays. The progress bar is implemented using a ProgressView in SwiftUI. The ProgressView is initialized with a label, a value, and a total. The value is a Double that represents the current progress of the audio player, and the total is a Double that represents the maximum progress. In this code, the value is the progress variable, and the total is fixed at 1.0. The progress variable is updated every second by the updateProgress function, which divides the current time of the audio player by its duration. This allows the progress bar to accurately reflect the current position of the audio. The ProgressView is also given an id to ensure that it updates every time the progress variable changes.

There are several ways that you can customize this code to fit your own needs. Here are a few ideas:

  1. Change the audio file: You can change the audio file that is played by specifying a different file name and extension in the Bundle.main.url(forResource: "Guided Meditation Compassion", withExtension: "m4a") line of code.

  2. Add more controls: You can add additional controls, such as a slider for adjusting the volume or a button for skipping to the next track.

  3. Change the appearance: You can customize the appearance of the buttons and progress view by using different images or colors.

In this article, we examined a SwiftUI code for creating an audio player that allows users to play, pause, and stop a guided meditation audio file, as well as track the progress of the audio with a progress bar. We looked at how the code works and discussed some ways to customize it to fit your own needs. By using AVFoundation and UIKit, it is possible to create a user-friendly audio player in SwiftUI that provides a seamless audio playback experience for your users.

I hope that this tutorial has been helpful and that you have gained some insight into how to create an audio player in SwiftUI. If you would like to stay up-to-date with the latest developments in Swift and iOS development, be sure to sign up for my newsletter, where you can find the latest tutorials, tips, and best practices for building iOS apps with Swift. Happy coding!

Did you find this article valuable?

Support Jake Watembach by becoming a sponsor. Any amount is appreciated!