using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.Networking; public class MusicPlayer : MonoBehaviour { private AudioSource audioSource; public string[] MusicFiles; // 用於儲存 MP3 檔案的路徑 public int currentTrackIndex = 0; // 目前正在播放的音樂索引 public bool isPaused = false; // 控制是否暫停 void Start() { audioSource = gameObject.GetComponent(); MusicFiles = Directory.GetFiles(@"C:\MyFiles", "*.mp3"); if (MusicFiles.Length > 0) { StartCoroutine(PlayTrack(currentTrackIndex)); // 播放第一首音樂 } else { Debug.LogError("資料夾沒有音樂檔案!"); } } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { if (audioSource.isPlaying) { audioSource.Pause(); // 當按下空白鍵時,播放或暫停音樂 isPaused = true; } else { if (isPaused) { audioSource.UnPause(); // 如果是暫停狀態則繼續播放 } else { StartCoroutine(PlayTrack(currentTrackIndex)); // 播放當前音樂 } isPaused = false; } } if (Input.GetKeyDown(KeyCode.UpArrow)) { PlayPreviousTrack(); // 使用上鍵切換到上一首音樂 } if (Input.GetKeyDown(KeyCode.DownArrow)) { PlayNextTrack(); // 使用下鍵切換到下一首音樂 } if (!audioSource.isPlaying && !isPaused) { PlayNextTrack(); // 當音樂播放完畢時,自動播放下一首 } } IEnumerator PlayTrack(int index) { if (MusicFiles.Length > 0) { string url = "file:///" + MusicFiles[index]; // 建立檔案路徑 URL using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG)) { yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError) { Debug.LogError("Error loading track: " + www.error); } else { AudioClip clip = DownloadHandlerAudioClip.GetContent(www); audioSource.clip = clip; audioSource.Play(); } } } } void PlayNextTrack() { currentTrackIndex = (currentTrackIndex + 1) % MusicFiles.Length; StartCoroutine(PlayTrack(currentTrackIndex)); } void PlayPreviousTrack() { currentTrackIndex--; if (currentTrackIndex < 0) { currentTrackIndex = MusicFiles.Length - 1; } StartCoroutine(PlayTrack(currentTrackIndex)); } }