开发者

AVAudioPlayer currentTime exceeds duration

I'm making my own audio player using AVAudioPlayer.

NOTE: "p" is my instance of the player

Here's how I'm reading the track progress in one of the labels:

currentTime.text = [NSString stri开发者_C百科ngWithFormat:@"%d:%02d", (int)p.currentTime / 60, (int)p.currentTime % 60];

Here's how I set the total duration of the track in one of the labels:

int seconds = (int)p.duration % 60;
    int minutes = (int)p.duration / 60;

    duration.text = [NSString stringWithFormat:@"%d:%02d", minutes, seconds];

When I run the app on the device, the track's current time ALWAYS exceeds the duration (by about 5-10 seconds).

Is this a bug in AVAudioPlayer, or am I not doing it correctly?

NOTE: This behavior also occurs on the device (not just on the simulator)


After finding the seconds by using % 60, you should remove those seconds when converting the remaining for the minutes. For e.g., with the total duration of 119 seconds after finding 59 seconds you should remove that from 119 and then do minute conversion for 60 seconds (119-59). That might solve your problem.


Minutes should be float: 152 seconds / 60.0f = 2.5333 not 2. That being said, if you want to show the remaining minutes without the seconds you already obtain: int minutes = (p.duration-seconds) / 60

Also, for a better method to format time the way you want to, have a look at the second answer in this question (not the accepted solution).


Here is the function:

func setTimeString(duration: Double)->String {

    var audioDurationSeconds = duration
    var expression = ""
    var minutesString = "00"
    var minutesFloat = 0.0

    if (audioDurationSeconds)/60 >= 1 {

        minutesFloat = (audioDurationSeconds) / 60
        audioDurationSeconds = TimeInterval(Int(audioDurationSeconds)%60)

        if minutesFloat < 10.0 {
            minutesString = String.init(format: "0%.f", floor(minutesFloat))

        } else {
            minutesString = String.init(format: "%.f", floor(minutesFloat))
        }
    }

    if audioDurationSeconds < 10.0 {
        expression = String.init(format: "%@:0%i", minutesString, Int(audioDurationSeconds))
    } else {
        expression = String.init(format: "%@:%i", minutesString, (Int(audioDurationSeconds)))
    }

    return expression
}


extension UILabel{

    func getTimeString(from duration:Double) -> String{

        let hours   = Int(duration / 3600)
        let minutes = Int(duration / 60) % 60

        let seconds = Int(duration.truncatingRemainder(dividingBy: 60))
        if hours > 0 {
            return String(format: "%i:%02i:%02i", arguments: [hours,minutes,seconds])
        }else {
            return String(format: "%02i:%02i", arguments: [minutes,seconds])
        }

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜