TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Timers and playing sound app

Forums > SwiftUI

Hi folks!

Im trying to make an app with 4 counters and audio player. If counting stop audio file will stop playing.

I have my basic layout and some logic but im stuck at few things. I wonder if you could take a look and guide me somehow? :)

For now problems are:

  1. file dont play cause "Audio file could not be found." - i have it in Assets.
  2. Im not sure how to fire timers using my buttons. This TimerViewModel class i got from ChatGPT and im not sure its correct..Looks to complicated for me.

ContentView:

import SwiftUI
import AVFoundation

class AudioPlayerViewModel: ObservableObject {
  var audioPlayer: AVAudioPlayer?

  @Published var isPlaying = false

  init() {
      if let sound = Bundle.main.path(forResource: "thesound", ofType: "mp3", inDirectory: "Assets") {
      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
    }
  }

}

class TimerViewModel: ObservableObject {
    @Published var timerCounts: [Int] = [0, 0, 0, 0]

    private var timers: [Timer] = []
    private let minutes = [15, 30, 45, 60]

    init() {
        setupTimers()
    }

    private func setupTimers() {
        for (index, minute) in minutes.enumerated() {
            let seconds = minute * 60
            let timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(seconds), repeats: true) { [weak self] _ in
                guard let self = self else { return }
                print("Timer \(index + 1) fired!")
                self.timerCounts[index] += 1
            }
            RunLoop.main.add(timer, forMode: .common)
            timers.append(timer)
        }
    }
}

struct ContentView: View {
  @StateObject var audioPlayerViewModel = AudioPlayerViewModel()
//    @StateObject private var timerViewModel = TimerViewModel()

  var body: some View {

      ZStack {

          Color.black
              .ignoresSafeArea()
          VStack {
              Spacer()
              // Here i want to show somehow time remaining 
              Spacer()
              Button(action: {
            audioPlayerViewModel.playOrPause()
          }) {
            Image(audioPlayerViewModel.isPlaying ? "pause" : "play")
              .resizable()
              .scaledToFit()
              .frame(width: 80, height: 80)
              .foregroundColor(.white)

          }
              Spacer()
              HStack(spacing: 60) {
                  Button(action: {
                      // fire the timer
                  }) {
                      Text("15")
                          .foregroundColor(.white)
                          .whiteTextWithCircularBorder()
                  }

                Button(action: {
                      // fire the timer
                  }) {
                      Text("30")
                          .foregroundColor(.white)
                          .whiteTextWithCircularBorder()
                  }

                  Button(action: {
                      // fire the timer
                  }) {
                      Text("45")
                          .foregroundColor(.white)
                          .whiteTextWithCircularBorder()
                  }
                  Button(action: {
                      // fire the timer 
                  }) {
                      Text("1 h")
                          .foregroundColor(.white)
                          .whiteTextWithCircularBorder()
                  }

              }
              Spacer()
        }

      }

  }
}

extension Text {
    func whiteTextWithCircularBorder() -> some View {
        self
            .overlay(
                Circle()
                    .stroke(Color.white, lineWidth: 1)
                    .frame(width: 50, height: 50)

            )
    }
}

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.