Search code examples
iosswiftswiftuiavaudioplayer

How to add current date with Song end time in swiftui?


I want to add the current time (Date()) and AVAudioPlayer total time song time (play.duration) together to get at what time song ends?

func play(){
let path = Bundle.main.path(forResource: "song", ofType:"mp3")!
    let url = URL(fileURLWithPath: path)
    do{
        player = try AVAudioPlayer(contentsOf: url)
        
        let endDate = Date() + player.duration
        if player.isPlaying{
            
            player.pause()
            
        }
        else{
            player.play()
         }
        isPlaying = player.isPlaying
    }catch{print("error")}
}

This is my view

VStack {
         
         Text("I want to display the ending time here")

        }

Solution

  • We can add TimeInterval which is a double to a Date

    A TimeInterval value is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years.

        Date() + 60 //<- 1 Second 
    
        let endDate = Date() + avPlayer.duration
    
    struct ContentView: View {
        @ObservedObject var viewModel = MyViewModel() //<- here
        
        var body: some View {
            VStack {
                
                Text(viewModel.endTime) //<- here
                
            }
        }
    }
    
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    

    In your ViewModel

    class MyViewModel: ObservableObject {
        @Published var endDate: Date? //<- here
        
        var endTime: String{
        if endDate == nil {
            return ""
        }else {
            var dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "hh:mm"
            return dateFormatter.string(from: endDate)
        }
    }
    
        func play(){
            let path = Bundle.main.path(forResource: "song", ofType:"mp3")!
            let url = URL(fileURLWithPath: path)
            do{
                player = try AVAudioPlayer(contentsOf: url) //<-here
                
                endDate = Date() + player.duration
                if player.isPlaying{
                    
                    player.pause()
                    
                }
                else{
                    player.play()
                }
                isPlaying = player.isPlaying
            }catch{print("error")}
        }
    }