- Home /
Get AudioClip from Path?,How to get AudioClip from a path?
Hiya. I am working on a project in Unity, and I've gotten stuck. I want the player to be able to select an audio file from their PC and have my program add it to a playlist to be listened to. I have a functional Playlist, and I can create space for a new song and open the explorer to let the player choose a file, but I can't get program to add the AudioClip to the playlist.
public AudioClip[] currentPlaylist;
string path;
public AudioClip newSong;
public void OpenExplorer()
{
path = EditorUtility.OpenFilePanel("Add Song", "", "mp3");
GetSong();
}
void GetSong()
{
if (path != null)
{
UpdatePlaylist();
}
}
void UpdatePlaylist()
{
WWW www = new WWW("file:///" + path);
newSong = www.GetAudioClip();
Array.Resize(ref currentPlaylist, (currentPlaylist.Length+1));
currentPlaylist[currentPlaylist.Length-1] = newSong;
}
I'm scratching my head at what isn't working, and I'm not sure if I need to make a fix to a bug here or if I just need to use a totally new approach. Sorry if this is a really simple question.
Very important note is that EditorUtility
does not work in a built game, as the name suggests, it's an editor only function.
Thank you very much for noting that, I will keep that in mind and update my method of selecting a file accordingly.
Answer by NikkF · Mar 23 at 10:49 PM
Here's the code I use when getting audio files from the machine. In this example, I save all of the clips to a list using public List<AudioClip> clips;
and call the method by calling LoadAudio(filename);
Filename is the name of the actual file ("song.mp3") and the path is something like "C:\Users\User\Desktop".
Here's the code for getting the file and adding it to the list;
private IEnumerator LoadAudio(string name)
{
WWW request = GetAudioFromFile(soundPath, name);
yield return request;
audioClip = request.GetAudioClip();
audioClip.name = name;
clips.Add(audioClip);
}
private WWW GetAudioFromFile(string path, string filename)
{
string audioToLoad = string.Format(path + "{0}", filename);
WWW request = new WWW(audioToLoad);
return request;
}
If you have any problems or questions, let me know.
Hope this helps!