Hi, I'm trying to create a slider that lets players control the playback of ambience or music tracks.
I've got an AC menu with a slider linked to a Unity slider and a custom script. The AC slider controls a float variable.
I can make it work with with game objects with the following script. But can't seem to work out how to hook it up to music or ambiance tracks!
audioSource = FindObjectOfType<AudioSource>();
if (audioSlider != null)
{
audioSlider.maxValue = audioSource.clip.length;
audioSlider.value = audioSource.time; // Initialize slider value with the current time of audio
audioSlider.onValueChanged.AddListener(OnSliderValueChanged);
}
}
void Update()
{
if (audioSource.isPlaying)
{
audioSlider.value = audioSource.time;
}
}
Is my setup wrong?
It looks like you're new here. If you want to get involved, click one of these buttons!
Comments
The AudioSource of Music and Ambience tracks respectively can be gotten with:
Thanks so much. Unfortunately, I'm a bit stuck with my custom scripts (I am not a developer).
This AI-written script does everything right, but I am struggling to make the slider stretch based on the length of the audio clip!
As in, it's physical size? That's a case of affecting the slider's RectTransform sizeDelta value, i.e.:
Sorry, I wasn't super clear about the issue (note that I'm not using the slider to control music anymore, but to control audio clips played using the Sound > Play action list).
The slider works fine and the player can click it to "scrub" the audio. But it only works with the latest sound object I add to the scene.
If I only have one sound object in the scene, I can get the slider to work on multiple clips by playing sounds using Sound > Play > New clip, but the min and max values are still linked to the length of the original audio resource.
I feel like I'm missing something to get the right length of the audio clip - and/or to detect the right clip that is playing. Is that something AC should be able to do?
It's not due to AC. Your script is setting the min/max values in the Start function - i.e. when the scene begins.
Detecing the "right clip that is playing" is open ended - multiple clips can play at the same time, technically. Are you looking to just affect the most recent to start? You can hook into the OnPlaySound event to extract it there instead of Start.
That is, replace:
with:
Yes! Thank you so much for the support!
Full updated script in case anyone else wants to achieve something similar: