5.准备播放和暂停两个UI素材

发布时间:2025-06-24 19:02:18  作者:北方职教升学中心  阅读量:876


5.准备播放和暂停两个UI素材。

一、

二、上代码。

        直接找个地方放代码,然后依次拖动刚刚创建的内容。

前言。拼UI。

4.创建两个Text,分别是当前的进度时间和总音频时间。

目录。

1.添加AudioSource￰的新空物c;为AudioSource添加音频文件༌取消对PlayOnawake的勾选c;检查Loop。

        另外,作者向playsprite和pausesprite拖动了播放和暂停的两张图片材料,随便找个两张图片代替就行了,否则会报空哈~。

        直接找个地方放代码,然后依次拖动刚刚创建的内容。上代码。

2.创建Slider󿀌用于控制音频进度。

3.创建Button󿀌控制播放和暂停。


前言。

代码如下:

using UnityEngine;using UnityEngine.UI;public class SZJCAudioProgressBar : MonoBehaviour{    public AudioSource audioSource;        // 音频源    public Slider progressBar;              // 进度条    public Text currentTimeText;            // 当前时间文本    public Text totalTimeText;              // 总时间文本    public Button playPauseButton;          // 播放/暂停按钮    public Sprite playSprite;//播放图片    public Sprite PauseSprite;//暂停图片    private bool isPlaying = false;         // 播放状态标记    void Start()    {        // 将 Slider 的值设置为 0        progressBar.value = 0;        // 设置总时间文本        totalTimeText.text = FormatTime(audioSource.clip.length);        // 添加事件监听器        progressBar.onValueChanged.AddListener(OnProgressBarValueChanged);        // 点击事件添加按钮        playPauseButton.onClick.AddListener(TogglePlayPause);    }    void Update()    {        // 更新进度条和当前时间文本的值        if (audioSource.isPlaying)        {            progressBar.value = audioSource.time / audioSource.clip.length;            currentTimeText.text = FormatTime(audioSource.time);        }        else if (audioSource.time >= audioSource.clip.length) // 检查播放是否完成        {            // 将播放状态设置为 false            isPlaying = false;            playPauseButton.GetComponent<Image>().sprite = playSprite; // 按钮文本更新            progressBar.value = 1; // 将进度条设置为满            currentTimeText.text = FormatTime(audioSource.clip.length); // 更新当前时间文本的总时间        }    }    // 切换播放和暂停状态    private void TogglePlayPause()    {        if (isPlaying)        {            audioSource.Pause();            playPauseButton.GetComponent<Image>().sprite = playSprite; // 按钮文本更新        }        else        {            audioSource.Play();            playPauseButton.GetComponent<Image>().sprite = PauseSprite; // 按钮文本更新        }        isPlaying = !isPlaying; // 切换播放状态    }    // 当 Slider 调用此方法进行值变化    private void OnProgressBarValueChanged(float value)    {        if (value < 1)        {            // 音频播放时间根据进度条的值设定            audioSource.time = value * audioSource.clip.length;        }    }    // 格式化时间为 "分:秒" 格式    private string FormatTime(float time)    {        int minutes = Mathf.FloorToInt(time / 60);        int seconds = Mathf.FloorToInt(time % 60);        return string.Format("{0:00}:{1:00}", minutes, seconds);    }}。

 效果如图所示:(因为GIF格式,不录音频�


一、

二、拼UI。