How to play sounds loaded on the fly

10,959

If you want to load files from the same directory as the .exe / .app you can use this :

  • Using the System.IO DirectoryInfo() to get all files names
  • Using the WWW class to stream/load the files found

Here the code :

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class SoundPlayer : MonoBehaviour {

    string absolutePath = "./"; // relative path to where the app is running

    AudioSource src;
    List<AudioClip> clips = new List<AudioClip>();
    int soundIndex = 0;

    //compatible file extensions
    string[] fileTypes = {"ogg","wav"};

    FileInfo[] files;

    void Start () {
        //being able to test in unity
        if(Application.isEditor)    absolutePath = "Assets/";
        if(src == null) src = gameObject.AddComponent<AudioSource>();
        reloadSounds();
    }

    void reloadSounds() {
        DirectoryInfo info = new DirectoryInfo(absolutePath);
        files = info.GetFiles();

        //check if the file is valid and load it
        foreach(FileInfo f in files) {
            if(validFileType(f.FullName)) {
                //Debug.Log("Start loading "+f.FullName);
                StartCoroutine(loadFile(f.FullName));
            }
        }
    }

    bool validFileType(string filename) {
        foreach(string ext in fileTypes) {
            if(filename.IndexOf(ext) > -1) return true;
        }
        return false;
    }

    IEnumerator loadFile(string path) {
        WWW www = new WWW("file://"+path);

        AudioClip myAudioClip = www.audioClip;
        while (!myAudioClip.isReadyToPlay)
        yield return www;

        AudioClip clip = www.GetAudioClip(false);
        string[] parts = path.Split('\\');
        clip.name = parts[parts.Length - 1];
        clips.Add(clip);
    }
}

[EDIT]

If people wants to improve on the file management I recommend this link

Share:
10,959
Lego
Author by

Lego

Updated on July 25, 2022

Comments

  • Lego
    Lego almost 2 years

    I trying to make a tool for the sound designer of my group that would allow him to hear his sound file played in Unity.

    • Check if it's loadable
    • Check if the volume is right
    • Check if loops properly

    and so on ...

    My issue is to find how Unity can manage loading audio files laying somewhere in a folder.

    I found a lot of topics speaking about it but no real solutions to how you can make Unity load external files dynamically.

  • Joetjah
    Joetjah about 11 years
    So, how do you 'Check if loops properly'? If you are going to answer your own question, please do so completely.
  • Max Yankov
    Max Yankov about 11 years
    I think that it's better to use Path.Combine ( msdn.microsoft.com/ru-ru/library/vstudio/fyy7a5kt(v=vs.90).a‌​spx ) to avoid platform-dependence.
  • StackUnder
    StackUnder about 11 years
    @Joetjah OP stated that the issue was only to find how Unity could manage loading audio files