Determine end of audio clip if paused and resumed inbetween?
I'm building a kind of music player into my app. The audio source can be paused and resumed but when the audio clip is completey finished, there needs to be a sprite swap and a variable needs to change.
If the audio is paused inbetween I obviously can't just use a coroutine that waits the lenght of the audio clip before it sets the new state.
Is there any build-in way to determine the end of the clip in this case? Or do I have to use some sort of coroutine that gets paused and resumed as well?
Answer by CHG_Eve · Nov 17, 2016 at 10:05 PM
Alrighty, I will answer my own question. As per usual I found the answer ten minutes after I posted the question.
I have an int variable for the music player that gets set to "stop"(0), "pause"(1) or "play"(2) whenever the user presses the according button.
My first attempt was with AudioSource.time. I wanted to compare the playback time with the clip length. This doesn't work because the lengt of the clip was not (exactly) identical to the playback time when the audio source stops and returns 0 again. Clip length was 13.0351. But the audio source stopped automatically at 13.035, so it never recognized the end of the clip / length.
Solution: In the update function: Check if the audio source is not playing but player state is still set to "play"
// if audio source stops, but my variable is still set to "play"
if (!MyAudioSource.isPlaying && audioState == 2) {
ToggleStop(); // activate my stop function that swaps sprite etc.
}
Tadaa!