Using the lenght of the audio clip instead of a magic number

using a magic number for the tween interval duration was driving us nuts.
after a quick dive into the docs we found audiostreamplayer has a stream property and that stream property has a get_length method.

we replaced:
tween.tween_interval(2.5)
with:
tween.tween_interval(explosion_audio.stream.get_length())

now the tween ends at the same time as the audio

12 Likes

Nice one for sharing, yeah that’s what I done in mine +1s.

Least that way you can change audio clip and it works. :+1:

Nice one, was looking at how to do that. Thanks

Good one. With this you don’t have to find out, how long sounds clips really are :slight_smile:

Really nice advice, thanks :exploding_head: :pray:t5:

You can also do this, which I think is even simpler.

explosion_audio.play()
await explosion_audio.finished
6 Likes

That’s what I did on mine too! It’s more accurate than waiting an amount of seconds equal to the stream length in my opinion.

Worth noting that with this approach, you no longer need a tween or a timer, since this approach is considered a replacement for those two :slight_smile:

Example code:

func crash_sequence() -> void:
	is_transitioning = true
	print("Kaboom!")
	freeze = true
	explosion_audio.play()
	await explosion_audio.finished
	freeze = false
	get_tree().reload_current_scene()

I couldn’t find a great example for this in C# along the lines of await so here is how I did it using the GetLength like the original poster:

	private double GetTransitionTime(AudioStreamPlayer audioStream)
	{
		// get the length of the audio for the transition time or the defaultTransitionTime if it is longer than the audio
		double audioLength = audioStream.Stream.GetLength();  // Get the length of the audio
		return audioLength > defaultTransitionTime ? audioLength : defaultTransitionTime;
	}
	
	private void CompleteLevel(String nextLevelFile)
	{
		GD.Print("Level Complete");
		
		// get transition time based on the audio and start the audio
		var transitionTime = GetTransitionTime(successAudio);
		successAudio.Play();
		
		// stop processing while transitioning
		SetProcess(false);
		isTransitioning = true;
		
		// start the tween to wait before loading the next level
		var tween = CreateTween();
		tween.TweenCallback(Callable.From(() => GetTree().ChangeSceneToFile(nextLevelFile))).SetDelay(transitionTime);
	}

Privacy & Terms