Getting an audio clip from file via script

I’m trying to get an audio clip from a file in the games directory and play it using Unity 5.6.4. I can’t seem to get it to pull up a correct path and play the file. What am I doing wrong here?

string path = Path.Combine (Application.dataPath, "Audio/Music/Song Name.ogg");
WWW clipPath = new WWW (path);
print (clipPath);  //It displays a correct path but puts a back slash \ before the Audio folder.
//When I put a forward slash / before the Audio folder in the string, print only returns the path from the Audio folder onward.
AudioClip audioClip = clipPath.GetAudioClip ();
print (audioClip.name);  //This is null for some reason with the code as it currently is.
MusicManager.instance.newSong = audioClip;
MusicManager.instance.ChangeSong ();

Depending on the target build, Application.dataPath I don’t think always works correctly. If you can’t just tie the audioClip to a variable, you should use the StreamingAssets folder and load from there instead.

I suppose you could also use the Resources folder. It’s been awhile since I’ve used a Unity version that old. I seem to recall these being the ways to do audio back then.

Also note if you do have spaces in your filename, I’d suggest removing them. I feel like spaces use to create issues in the past.

Thanks for the response. I’ve been experimenting and I tried Resources.Load with no luck. I created a Resources folder within the Assets folder, put a Music folder in it, and put a song in that folder with no spaces in the filename and did the following:

AudioClip audioClip = Resources.Load ("Music/Song_Name.ogg") as AudioClip;
print (audioClip.name);

That gives a null reference error.

As a side note, I sure wish I could upgrade this game to a newer version of Unity but it relies on several deprecated assets. 5.6.4 was the newest version when I started work on it 6 years ago and I have around 6k hours invested in it. Hopefully I’ll finally have it finished and released this summer.

I just unexpectedly got it working! It seems that Resources.Load does not want to know the files extension. For anyone running across this in the future what worked was the following:

AudioClip audioClip = Resources.Load <AudioClip> ("Music/Song_Name");
1 Like