我有一个音频剪辑和一个滑块。滑块充当音频剪辑的进度条(时间线(。我可以暂停播放音频,也可以跳过音轨。一切都很好。问题是滑块移动不平稳,有点抖动。如果有人可以的话,请编辑一下。提前谢谢。
这是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MusicPlayer : MonoBehaviour
{
AudioSource audioSource;
Slider slider;
public AudioClip track;
// Start is called before the first frame update
void Start()
{
audioSource = GetComponent<AudioSource>();
slider = GetComponent<Slider>();
audioSource.clip = track;
audioSource.Play();
slider.minValue = 0;
slider.maxValue = track.length;
}
// Update is called once per frame
void Update()
{
slider.value = audioSource.time;
}
public void MovePoition()
{
audioSource.time = slider.value;
}
public void play()
{
audioSource.Play();
}
public void pause()
{
audioSource.Pause();
}
}
在Update
上,如果正在播放滑块,请使用Time.deltaTime
更新滑块的值以确保平滑度。否则,同样在play
和pause
中,将位置与播放时间重新同步。
但是,在设置值时需要避免回调。在Start
创建一个空事件,并在更新值时将其分配给滑块。
最后,添加一个标志来跟踪曲目是否应该播放。这样可以防止在播放片段结尾然后拖动滑块时停止源。
在MovePoition
中设置源时间后,根据剪辑的压缩情况,它可能无法设置为滑块的确切值。因此,您应该根据音频源决定使用的时间重新更新滑块值。
总计:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MusicPlayer : MonoBehaviour
{
AudioSource audioSource;
Slider slider;
Slider.SliderEvent emptyEvent;
public AudioClip track;
private bool isPaused;
private bool needSync;
// Start is called before the first frame update
void Start()
{
audioSource = GetComponent<AudioSource>();
slider = GetComponent<Slider>();
audioSource.clip = track;
audioSource.Play();
slider.minValue = 0;
slider.maxValue = track.length;
emptyEvent = new Slider.SliderEvent();
}
void SetSliderWithoutCallback(float time)
{
Slider.SliderEvent temp = slider.onValueChanged;
slider.onValueChanged = emptyEvent;
slider.value = time;
slider.onValueChanged = temp;
}
// Update is called once per frame
void Update()
{
if (audioSource.isPlaying)
{
float newTime = Mathf.Min(slider.value + Time.deltaTime, slider.maxValue);
SetSliderWithoutCallback(newTime);
}
else if (!isPaused)
{
SetSliderWithoutCallback(slider.maxValue);
isPaused = true;
}
}
public void MovePoition()
{
audioSource.time = slider.value;
if (!isPaused)
{
audioSource.Play();
SetSliderWithoutCallback(audioSource.time);
}
}
public void play()
{
audioSource.Play();
isPaused = false;
SetSliderWithoutCallback(audioSource.time);
}
public void pause()
{
isPaused = true;
audioSource.Pause();
SetSliderWithoutCallback(audioSource.time);
}
}