- Home /
How to get a list of AudioClips from a directory at runtime?
ok, so I'm making a music player and i need to get all mp3 files from a path in the computer, then store those files as a list of AudioClips that the AudioSource can play. The problem is, I have no clue on how to do this. Can anybody help me with this?
Answer by W01Fi3 · Oct 10, 2018 at 08:44 PM
@LeytonViner Well, after a lot of research and testing, I found a way to do this. Of course there's always a better way to do this but this is the best I can come up with
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
//Don't forget to use System.IO
public class GetAudioFiles : MonoBehaviour
{
//Directory of folder to be searched anywhere on the computer
public string FileDirectory;
//Audio source
public AudioSource Source;
//Current sound playing
public AudioClip Clip;
//List of all valid directories
List<string> Files = new List<string>();
//List of all AudioClips
List<AudioClip> Clips = new List<AudioClip>();
private void Start()
{
Source = GetComponent<AudioSource>();
//Grabs all files from FileDirectory
string[] files;
files = Directory.GetFiles(FileDirectory);
//Checks all files and stores all WAV files into the Files list.
for (int i = 0; i < files.Length; i++)
{
if (files[i].EndsWith(".wav"))
{
Files.Add(files[i]);
Clips.Add(new WWW(files[i]).GetAudioClip(false, true, AudioType.WAV));
}
}
//Calls the below method
PlaySong(0);
}
public void PlaySong(int _listIndex)
{
Clip = Clips[_listIndex];
Source.clip = Clip;
Source.Play();
}
}
Remember to make sure all files are WAV files, and to assign the FileDirectory variable, or even make an array of directories
Did you test this? for some reason theres an error about fmod when trying to add the song to the clips
Ok, I just tested it and everything works fine.
All you need to do is assign the variable FileDirectory to a valid local file path on your computer As well as that, ensure that all audio files at that path are .wav files, else it will not work. Obviously, you need an audio source on the object the script is attached to, or assigned Source to any audio source within the scene
what version are you using? it doesnt work in 2017.3