unity3d 在Unity中按下播放时,使用滑块显示音频源的进度

nhjlsmyf  于 2022-12-19  发布在  其他
关注(0)|答案(2)|浏览(349)

我正在建立一个应用程序,用户点击一个按钮,一个音频源播放。有暂停和退出的选项。
我试着整合一个滑动条来显示进度。

{
    [Header("List of Tracks")]
    [SerializeField] private Track[] audioTracks;
    
    private int trackIndex; 
    
    [Header("Text UI")]
    [SerializeField] private TextMeshProUGUI trackTextUI;
    
    private AudioSource audio;
            
    // Start is called before the first frame update
    private void Start()
    {
        audio = GetComponent<AudioSource>();
        
        audio.clip = audioTracks[trackIndex].trackAudioClip;
        
        trackTextUI.text = audioTracks[trackIndex].name;
                
    }
    
    public void FiveMinuteMed()
    {
        trackIndex = 0;
        audio.Play();
    }
    
    public void TenMinuteMed()
    {
        trackIndex = 1;
        audio.Play();   
        
    }
    
    public void FifteenMinuteMed()
    {
        trackIndex = 2;
        audio.Play();
    }

  public void PlayAudio()
  {
      audio.Play();
  }
  
  public void PauseAudio()
  {
      audio.Pause();
  }
  
   public void StopAudio()
  {
      audio.Stop();
  }
  
 }

我试着把下面的代码段添加到on Update()函数中..显然是在start上声明变量等。当我点击play..应用程序就冻结了..

public Slider time;
public AudioSource audio;
// Start is called before the first frame update
void Start()

    {
        audio = GetComponent<AudioSource>();
    }
    
    // Update is called once per frame
    void Update()
    {
        time.maxValue = audio.clip.length;
        time.value = audio.time;
        audio.time = time.value;
    }

有什么想法,我可以把滑块在原来的代码片段以上..?

xxb16uws

xxb16uws1#

删除这一行,看看它是否工作:
第一个月

dgsult0t

dgsult0t2#

您可以使用UI Toolkit for Unity。ProgressBar将用于此场景。一种方法如下所示:

public AudioSource source;
public float progress;
public UIDocument document;

VisualElement root;
ProgressBar progressBar;

void Awake()
{
    // getting the root visual element
    root = document.rootVisualElement;
    // getting the progress bar
    progressBar = root.Q<ProgressBar>("progressBar");
}

void Start()
{
    // setting up the title of the progress bar
    progressBar.title = source.clip.name;
}

void Update()
{
    // calculating the progress as percent because
    // the min and max values of the progress bar read-only
    progress = source.time / source.clip.length * 100;
    progressBar.value = progress;

    // debug to check the progress
    Debug.Log(progress + "%" + " out of " + source.clip.length + " seconds");
}

我已经测试的代码和它的工作正常。如果你想要一个滑块,你可以很容易地转换成一个支持滑块此代码。
只需将类型从ProgressBar更改为Slider

相关问题