如何在 swiftui 中添加当前日期和歌曲结束时间?

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

我想把当前时间(Date())和AVAudioPlayer总时间歌曲时间(play.duration)加起来得到歌曲结束的时间?

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

这是我的看法

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

        }

我们可以将 TimeInterval 添加到 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()
    }
}

在您的 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")}
    }
}