Sound should end when sec is in a specific number

Lets say the Sound is 10 sec long

and the Number is from 1 to 30 seconds

The Sound should get slower so the sound can run 30 sec long.

Or if its 1 to 20 seconds the Sound should be slower and end in 20 sec, how can i do that?

local sound = pathtosound --Where the sound is
local length = 30 --How long you want

local factor = sound.TimeLength / length
sound.PlaybackSpeed = factor

sound:Play()

Something like this should work