add more randomness to the track selector and add functionality to the script where if…
- User
add more randomness to the track selector and add functionality to the script where if the song is over then play another random song
using UnityEngine; using System.Collections;
public class RandomSoundPlayer : MonoBehaviour { public AudioClip[] soundClips; // List of sound clips public AudioSource audioSource; public AnimationClip clip; public void Awake() { Play(25); }
public void StopIt() { Stop(clip.length - 2); } // Play a random sound clip with fade-in effect public void Play(float fadeInDuration) { if (soundClips.Length == 0) { Debug.LogWarning("No sound clips assigned!"); return; } // Select a random sound clip AudioClip randomClip = soundClips[Random.Range(0, soundClips.Length)]; audioSource.clip = randomClip; audioSource.volume = 0; // Start volume at 0 audioSource.Play(); // Start the fade-in coroutine StartCoroutine(FadeIn(fadeInDuration)); } // Stop the sound with a fade-out effect public void Stop(float fadeOutDuration) { // Start the fade-out coroutine StartCoroutine(FadeOut(fadeOutDuration)); } private IEnumerator FadeIn(float duration) { float targetVolume = 0.6f; float startVolume = audioSource.volume; float elapsed = 0.0f; while (elapsed < duration) { elapsed += Time.deltaTime; audioSource.volume = Mathf.Lerp(startVolume, targetVolume, elapsed / duration); yield return null; } audioSource.volume = targetVolume; // Ensure volume is set to target } private IEnumerator FadeOut(float duration) { float startVolume = audioSource.volume; float elapsed = 0.0f; while (elapsed < duration) { elapsed += Time.deltaTime; audioSource.volume = Mathf.Lerp(startVolume, 0, elapsed / duration); yield return null; } audioSource.Stop(); audioSource.volume = startVolume; // Reset volume to original for next use }}
- Assistant