- Home /
UI Slider Audio lenght
Hello, I am making an app for android, and I'm trying to set the value of the slider according to the time of the audio clip. I can move the slider, which forwards or rewinds to moments of the audio clip, but i can not make it move on it's own without any bugs. When i press play, the audio starts, it moves the slider, but it stutters, like i can hear it 2-3 times at once. I think it's because the slider.value is set to be modified in an update function. IDK guys, any help is greatly appriciated. Here's the code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class AudioSlider : MonoBehaviour {
public Slider audioSlider;
void Start () {
audio.Play();
audioSlider.direction = Slider.Direction.LeftToRight;
audioSlider.minValue = 0;
audioSlider.maxValue = audio.clip.length;
}
void Update () {
audioSlider.value = audio.time;
}
}
P.S Nothing changes when "Play on awake" on the audiosource is checked/unchecked.
I have a solution for that, I'll share it once I get home.
here is a demo of the result. ( I dunno if the webplayer will work for you as it is now restricted by google, the app is slow to load).
I used the unity slider, grab the yellow bug to navigate in the song.
Answer by Nerevar · Jun 26, 2015 at 07:41 AM
Hello,
So I actually use this solution :
public Slider TimeLine;
// Flag to know if we are draging the Timeline handle
private bool TimeLineOnDrag = false;
void Update(){
if (TimeLineOnDrag) {
audio.timeSamples = (int)(audio.clip.samples * TimeLine.value);
}
} else {
TimeLine.value = (float)audio.timeSamples / (float)clip audio.clip.samples;
}
}
// Called by the event trigger when the drag begin
public void TimeLineOnBeginDrag(){
TimeLineOnDrag = true;
audio.Pause();
}
// Called at the end of the drag of the TimeLine
public void TimeLineOnEndDrag(){
audio.Play();
TimeLineOnDrag = false;
}
I pause the audio while I move the handle that's better for the user's ears. Put the script where you have your AudioSource, reference the slider and link the last 2 function to the event trigger (for example OnMouseDown and OnMouseUp).
Answer by M_Kumar · Jan 19 at 07:50 AM
IEnumerator Start()
{
slider.maxValue = audioSource.clip.length;
slider.value = audioSource.time;
while (audioSource.isPlaying)
{
slider.value = audioSource.time;
UnityEngine.Debug.LogError("VALUE IS "+(audioSource.clip.length/audioSource.time));
yield return null;
}
yield return null;
}
You can then attach this function ( OnSliderValueChanged) to the Slider OnValueChanged event.
public void OnSliderValueChanged ()
{
audioSource.time = slider.value;
}
Your answer
