Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play sounds loaded on the fly

Tags:

c#

unity3d

audio

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.

like image 800
Lego Avatar asked Apr 11 '13 11:04

Lego


1 Answers

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

like image 118
Lego Avatar answered Oct 09 '22 11:10

Lego