0 votes

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

in Engine by (59 points)

1 Answer

+2 votes
Best answer

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)
by (5,192 points)
selected by

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 :)

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.