Frage

When I change the rate on one of my AVAudioPlayers and then call currentTime on it later, I get the wrong value back. Why is this?

For example, this code doesn't work like I expect it to:

AVAudioPlayer* myAudio = //set up AVAudioPlayer
myAudio.enableRate = YES;
myAudio.rate = 1.2;

[myAudio play];

// Wait 3 seconds

myAudio.currentTime; //Returns a value significantly larger than 3.0 
War es hilfreich?

Lösung

When you call AVAudioPlayer.currentTime, it returns how far the audio would be into playing if it's rate was 1.0. When you change the rate, the value that currentTime returns changes proportionately.

Put another way, AVAudioPlayer.duration doesn't change when you change rate, and myAudioPlayer.currentTime / myAudioPlayer.duration will always tell you what portion of the audio file has played. So if you evaluate that expression when half the audio file has played, it will return roughly 0.5, regardless of what the rate is.

This means that if myAudio.rate < 1.0, myAudio.currentTime will consistently return a value less than how long the user has been listening to the audio. Conversely, if myAudio.rate > 1.0, myAudio.currentTime will consistently return a value longer than how long the user has been listening.

If you want to get how long the user has been listening, you can calculate it easily: myAudio.currentTime / myAudio.rate.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top