How can I change speed of an audio (without changing its pitch)?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By godot.ma.desive.logo

Hello!
how can I change tempo of an audio without changing its pitch? (from code, if it si possible)
Thank you for advice :smiling_face:

:bust_in_silhouette: Reply From: avencherus

Probably not ideal, but you can do something like that by changing the pitch_scale of the sample player, and then add it to a bus channel that has a pitch shifter audio affect, and set it’s scale to invert of the value you used. Buses and effects are easier set up through the Audio panel and the sample player’s bus property, but if you want a code only example, it would look something like:

extends Node2D # v3.2.4


const BUS_NAME  = "Pitch"
const BUS_INDEX = 1
const EFF_INDEX = 0

export var pitch = 2.0

# Replace with yours.
onready var sfx : AudioStreamPlayer = $AudioStreamPlayer



func _ready() -> void:
	
	var shift = AudioEffectPitchShift.new()
	
	shift.pitch_scale = 1.0 / pitch
	
	AudioServer.add_bus(BUS_INDEX)
	AudioServer.set_bus_name(BUS_INDEX, BUS_NAME)
	AudioServer.add_bus_effect(BUS_INDEX, shift, EFF_INDEX)
	
	sfx.bus = BUS_NAME


func _input(event: InputEvent) -> void:
	
	if(event.is_pressed()):

		sfx.play()
		sfx.pitch_scale = pitch
	
		var shift = AudioServer.get_bus_effect(BUS_INDEX, EFF_INDEX)

		shift.pitch_scale = 1.0 / pitch

		sfx.connect("finished", self, "ts", [], CONNECT_ONESHOT)
		ts = OS.get_ticks_usec()
	

var ts : float

func ts():
	print("SFX finished in: ", (OS.get_ticks_usec() - ts) / 1000000.0)

Yeah! It works!
(but it is relatively useless, because it lowers quality of an audio (even if it has normal playback speed), so for people who don’t care about it is it fine working solution).
Thank you :slight_smile:

godot.ma.desive.logo | 2020-12-02 14:37

Changing the audio playback speed without affecting pitch will always decrease quality, especially if you do it in a manner that’s compatible with real-time usage.

Otherwise, you have to edit the sound manually using Audacity or similar and export it again.

Calinou | 2020-12-02 17:32