Search Unity

Load sounds at runtime

Discussion in 'Audio & Video' started by meischder, Jun 25, 2015.

  1. meischder

    meischder

    Joined:
    Dec 28, 2013
    Posts:
    9
    Hi,

    is there a way to load any sound at runtime, e.g. using an command line argument with the path to a certain audio file? It wouldn't be a problem to be forced to put the sounds into a certain folder but as far as I see it's not possible to use the resources-folder which doesn't exist as a folder after building.

    Thanks
     
  2. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,304
  3. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Using the Resource folder after a build still works.
    Code (CSharp):
    1. public AudioClip music;
    2.  
    3. void Start(){
    4. //Load the sound
    5. music = (AudioClip) Resources.Load("Music");
    6. //Play the sound
    7. GameObject m = new GameObject("Music");
    8. m.AddComponent<AudioSource>();
    9. m.GetComponent<AudioSource>().clip = music;
    10. m.GetComponent<AudioSource>().Play();
    11. }
     
  4. meischder

    meischder

    Joined:
    Dec 28, 2013
    Posts:
    9
    Indeed, loading files from Resource-folder works but you're not able to put new files in it.
     
  5. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    I guess the only way would be by putting all the files you need into the Resources folder prior to making a build.
     
  6. Smoy

    Smoy

    Joined:
    Dec 8, 2014
    Posts:
    2
    Since Unity 5, you can use
    AudioClip.LoadAudioData();

    More info here here
     
  7. meischder

    meischder

    Joined:
    Dec 28, 2013
    Posts:
    9
    Thank you for you reply but I've got the WWW-solution working yesterday.
    For anyone who is interested in, here's the code:
    Code (CSharp):
    1.           WWW audioLoader = new WWW(text);
    2.           while (!audioLoader.isDone)
    3.                     System.Threading.Thread.Sleep(100);
    4.  
    5.           sound =audioLoader.GetAudioClip(true, false);
    6.  
    7.           int counter = 0;
    8.           while (sound == null){
    9.                     //do not load longer than 5seconds
    10.                     if (counter++ > 50)
    11.                               break;
    12.                     else
    13.                               System.Threading.Thread.Sleep(100);
    14.                         }
    15.  
    16.           sound = audioLoader.audioClip;
    Sincerely
     
  8. schashm3

    schashm3

    Joined:
    Oct 9, 2018
    Posts:
    10
    past this code in your project..

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.Networking;
    6. using System.IO;
    7.  
    8. public class PlayList : MonoBehaviour {
    9.  
    10.     string path;
    11.     public List<AudioClip> Cliplist;
    12.     AudioClip[] clips;
    13.  
    14.     public List<string> audioname;
    15.  
    16.     void Start ()
    17.     {
    18.         path = Application.persistentDataPath;
    19.        
    20.      
    21.         if (Directory.Exists(path))
    22.         {
    23.             DirectoryInfo info = new DirectoryInfo(path);
    24.          
    25.             foreach (FileInfo item in info.GetFiles("*.wav"))
    26.             {
    27.              
    28.                 audioname.Add(item.Name);
    29.             }
    30.          
    31.         }
    32.         StartCoroutine(LoadAudioFile());
    33.     }
    34.  
    35.     IEnumerator LoadAudioFile()
    36.     {
    37.         for (int i = 0; i <audioname.Count; i++)
    38.         {
    39.             UnityWebRequest AudioFiles = UnityWebRequestMultimedia.GetAudioClip(path + string.Format("{0}", audioname[i]),AudioType.WAV);
    40.             yield return AudioFiles.SendWebRequest();
    41.             if(AudioFiles.isNetworkError)
    42.             {
    43.                 Debug.Log(AudioFiles.error);
    44.                 Debug.Log(path + string.Format("{0}", audioname[i]));
    45.             }
    46.             else
    47.             {
    48.                 AudioClip clip = DownloadHandlerAudioClip.GetContent(AudioFiles);
    49.                 clip.name = audioname[i];
    50.                 Cliplist.Add(clip);
    51.                 Debug.Log(path + string.Format("{0}", audioname[i]));
    52.             }
    53.         }
    54.      
    55.     }
    56. }
    57.  
    58.  
     
  9. mattetti

    mattetti

    Joined:
    Nov 25, 2019
    Posts:
    1
    For those looking for a solution using async/await and potentially needing to first fetch the file and then play here, I posted an example generating an audio file using text to speech and then loading it into a clip to play it.

    Also, you can store the downloaded/generated file in `Application.dataPath` to easily get it back (the asset folder).

    Script: Unity script to generate and load an audio clip using Azure Cognitive Services (github.com)
    Full project (see readme): mattetti/UnityAzureSpeechSynthesis: Quick demo showing how to use Azure Speech Synthesis (tts) from Unity and loading/playing the generated file in game. (github.com)

    The short version is that you can use an async function such as:

    Code (CSharp):
    1.  public async Task<AudioClip> GetAudioClip(string filePath, AudioType fileType)
    2.     {
    3.  
    4.         using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(filePath, fileType))
    5.         {
    6.             var result = www.SendWebRequest();
    7.  
    8.             while (!result.isDone) { await Task.Delay(100); }
    9.  
    10.             if (www.result == UnityWebRequest.Result.ConnectionError)
    11.             {
    12.                 Debug.Log(www.error);
    13.                 return null;
    14.             }
    15.             else
    16.             {
    17.                 return DownloadHandlerAudioClip.GetContent(www);
    18.             }
    19.         }
    20.     }
    And call it to populate a predefined audio clip (or a new variable):

    Code (CSharp):
    1. _audioClip = await GetAudioClip(outputPath, AudioType.WAV);
    The clip can then be played via an AudioSource instance.

    Note that this approach works for remote files as well as local files.