赞
踩
音乐管理器,配置好对应组件
- using TMPro;
- using UnityEngine;
- using UnityEngine.UI;
-
- public class MusicPlayer : MonoBehaviour
- {
- private AudioSource audioSource;
- public AudioClip[] songs;
- private int currentSongIndex = 0;
- public TextMeshPro songNameText;// 引用UI文本组件
-
- [Header("ui组件")]
- public Text totalTimeText;
- public Text currentTimeText;
- public Slider timeSlider;
-
-
- private float totalDuration;
- private bool isPlay;
-
- private void Start()
- {
- audioSource = GetComponent<AudioSource>();
-
- PlayCurrentSong();
-
- timeSlider.onValueChanged.AddListener(OnSliderValueChanged);
- UpdateSongTimeText();
-
- }
- public void SwitchAudioPlayState()
- {
- if(isPlay)
- {
- PlayCurrentSong();
- }
- else
- {
- PauseMusic();
- }
- isPlay=!isPlay;
- }
- public void UpdateSongTimeText()
- {
- // 设置滑动条的最大值为1,因为时间范围为0到1
- timeSlider.maxValue = 1f;
-
- // 获取歌曲总时长
- totalDuration = audioSource.clip.length;
-
- // 更新总时长文本
- totalTimeText.text = FormatTime(totalDuration);
- }
-
- public void PlayCurrentSong()
- {
- if (audioSource != null && songs.Length > 0)
- {
- audioSource.clip = songs[currentSongIndex];
- audioSource.Play();
-
- UpdateSongNameText(); // 更新UI文本显示
- }
- }
-
- public void PauseMusic()
- {
- if (audioSource != null && audioSource.isPlaying)
- {
- audioSource.Pause();
- }
- }
-
- public void StopMusic()
- {
- if (audioSource != null && audioSource.isPlaying)
- {
- audioSource.Stop();
- }
- }
-
- public void NextSong()
- {
- currentSongIndex++;
- if (currentSongIndex >= songs.Length)
- {
- currentSongIndex = 0;
- }
- audioSource.time=0;
- PlayCurrentSong();
- UpdateSongTimeText();
- }
-
- public void PreviousSong()
- {
- currentSongIndex--;
- if (currentSongIndex < 0)
- {
- currentSongIndex = songs.Length - 1;
- }
- audioSource.time=0;
- PlayCurrentSong();
- UpdateSongTimeText();
- }
- public void FastForward(float seconds)
- {
- if (audioSource != null && audioSource.isPlaying)
- {
- audioSource.time += seconds;
- }
- }
- public void SlowForward(float seconds)
- {
- if (audioSource != null && audioSource.isPlaying)
- {
- audioSource.time -= seconds;
- }
- }
- private void UpdateSongNameText()
- {
- if (songNameText != null)
- {
- songNameText.text = songs[currentSongIndex].name;
- }
- }
-
- private void Update()
- {
- // 更新当前进行时间
- float currentTime = audioSource.time;
- currentTimeText.text = FormatTime(currentTime);
-
- // 更新滑动条的值
- timeSlider.value = currentTime / totalDuration;
-
- if (!audioSource.isPlaying&&!isPlay )
- {
- NextSong();
- }
- }
-
- public void OnSliderValueChanged(float value)
- {
- // 将滑动条的值映射到歌曲的时间范围内
- float targetTime = value * totalDuration;
-
- // 设置音频源的播放时间
- audioSource.time = targetTime;
- }
-
- 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);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。