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.
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).
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;
}
@Dalerjonjon this works for me (2021.3.5f1)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AudioSlider : MonoBehaviour
{
public Slider TimeLine;
private bool TimeLineOnDrag = false;
void Update()
{
if (TimeLineOnDrag)
{
GetComponent<AudioSource>().timeSamples = (int)(GetComponent<AudioSource>().clip.samples * TimeLine.value);
}
else
{
TimeLine.value = (float)GetComponent<AudioSource>().timeSamples / (float)GetComponent<AudioSource>().clip.samples;
}
}
public void TimeLineOnBeginDrag()
{
TimeLineOnDrag = true;
GetComponent<AudioSource>().Pause();
}
public void TimeLineOnEndDrag()
{
GetComponent<AudioSource>().Play();
TimeLineOnDrag = false;
}
}