Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Load Audio Files and keep runtime without freezing

Discussion in 'Scripting' started by dernat71, Apr 4, 2015.

  1. dernat71

    dernat71

    Joined:
    Jul 7, 2014
    Posts:
    14
    Hi guys !

    I'm currently developing an immersive audio visualiser . I success to load ( at Start() ) any audio files that is in the path of the application ( and with the .ogg & .wav extension ) . The problem is that it's freezing my Scene and it's pretty unconfortable .

    My idea is to make something similar to a thread and load all thoses audio files in background. And when loading is finished, create the AudioSource relative to my audio file ... I really want to minimize the freezing effect .

    Does someone can help me ?

    Thank you in advance !

    Here is my Audio Loading code :

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.IO;
    5. using System.Linq;
    6. public class MusicLoader : MonoBehaviour
    7. {
    8.  
    9.      bool Flag1Fois = false;
    10.    
    11.      float NombredeFichiers=0;
    12.  
    13.      public GameObject planète;
    14.      public enum SeekDirection { Forward, Backward }
    15.      public AudioSource source;
    16.      public List<AudioClip> clips = new List<AudioClip>();
    17.      [SerializeField] [HideInInspector] private int currentIndex = 0;
    18.      private FileInfo[] soundFiles;
    19.      private List<string> validExtensions = new List<string> { ".ogg", ".wav" }; // Don't forget the "." i.e. "ogg" won't work - cause Path.GetExtension(filePath) will return .ext, not just ext.
    20.      private string absolutePath = "./"; // relative path to where the app is running
    21.      void Awake()
    22.      {
    23.  
    24.          //being able to test in unity
    25.          if (Application.isEditor) absolutePath = "Assets/";
    26.  
    27.          Debug.Log("Nombre de Musique AVANT : " + clips.Count);
    28.          ReloadSounds();
    29.  
    30.      }
    31.  
    32.      void Update()
    33.      {
    34.  
    35.          if (clips.Count==NombredeFichiers && Flag1Fois==false) // Si le nombre de fichiers compatible == le nombre de fichiers chargé dans le tableau -> Lancer la génération
    36.          {
    37.              GameObject Planète;
    38.  
    39.              for (int i = 0; i < clips.Count; i++)
    40.              {
    41.  
    42.                  Planète = Instantiate(planète, GeneratedPosition(), Random.rotation) as GameObject;
    43.                  Planète.audio.clip = clips[i] as AudioClip;
    44.                  Planète.name = Planète.audio.clip.name;
    45.                  Planète.audio.Play();
    46.  
    47.              }
    48.  
    49.              Flag1Fois = true;
    50.  
    51.          }
    52.    
    53.      }
    54.      void Seek(SeekDirection d)
    55.      {
    56.          if (d == SeekDirection.Forward)
    57.              currentIndex = (currentIndex + 1) % clips.Count;
    58.          else {
    59.              currentIndex--;
    60.              if (currentIndex < 0) currentIndex = clips.Count - 1;
    61.          }
    62.      }
    63.      void PlayCurrent()
    64.      {
    65.          source.clip = clips[currentIndex];
    66.          source.Play();
    67.      }
    68.      void ReloadSounds() // Relance la procédure de chargement
    69.      {
    70.          clips.Clear();
    71.          // get all valid files
    72.          var info = new DirectoryInfo(absolutePath);
    73.          NombredeFichiers = DirCount(info);
    74.          Debug.Log("Nombre de Musiques détectées : "+ NombredeFichiers);
    75.          soundFiles = info.GetFiles()
    76.              .Where(f => IsValidFileType(f.Name))
    77.              .ToArray();
    78.      
    79.          // and load them
    80.          foreach (var s in soundFiles)
    81.              StartCoroutine(LoadFile(s.FullName));
    82.  
    83.        
    84.      }
    85.      bool IsValidFileType(string fileName)   // Check si l'extension est compatible
    86.      {
    87.          return validExtensions.Contains(Path.GetExtension(fileName));
    88.          // Alternatively, you could go fileName.SubString(fileName.LastIndexOf('.') + 1); that way you don't need the '.' when you add your extensions
    89.      }
    90.      IEnumerator LoadFile(string path)  // Charge les fichiers
    91.      {
    92.          WWW www = new WWW("file://" + path);
    93.          print("loading " + path);
    94.  
    95.          AudioClip clip = www.GetAudioClip(true);
    96.          while(!clip.isReadyToPlay)
    97.              yield return www;                
    98.          print("done loading");
    99.          clip.name = Path.GetFileName(path);
    100.          clips.Add(clip);
    101.  
    102.          Debug.Log("Nombre de Musiques APRES : " + clips.Count);
    103.  
    104.          DirectoryInfo dir = new DirectoryInfo(path);
    105.          FileInfo[] info = dir.GetFiles("*.*");
    106.  
    107.      
    108.        
    109.  
    110.      }
    111.  
    112.    
    113.      Vector3 GeneratedPosition()  // Génére les postions random des Sources audios
    114.      {
    115.  
    116.  
    117.  
    118.          Vector3 Centre = transform.localPosition;
    119.          Debug.Log(Centre);
    120.  
    121.  
    122.          float x, y, z;
    123.          x = Random.Range(Centre.x - 1000, Centre.x + 1000);
    124.          y = Random.Range(Centre.y - 1000, Centre.y + 1000);
    125.          z = Random.Range(Centre.z - 1000, Centre.z + 1000);
    126.          return new Vector3(x, y, z);
    127.  
    128.  
    129.      }
    130.  
    131.  
    132.    
    133.    
    134.      public static long DirCount(DirectoryInfo d)  // Fonction permettant de compter le nombre de .wav et .ogg dans le dossier
    135.      {
    136.          long i = 0;
    137.          // Add file sizes.
    138.          FileInfo[] fis = d.GetFiles();
    139.          foreach (FileInfo fi in fis)
    140.          {
    141.              if (fi.Extension.Contains("ogg"))
    142.                  i++;
    143.              if(fi.Extension.Contains("wav"))
    144.                 i++;
    145.          }
    146.  
    147.          return i;
    148.      }
    149.  
    150.  
    151. }
    152.  
    153.  
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Instead of loading them all at once, what about adding them to a list and processing them over time? You could either process X files per frame or run a timer (like the Stopwatch class) and stop after so many milliseconds have passed.
     
  3. dernat71

    dernat71

    Joined:
    Jul 7, 2014
    Posts:
    14
    It will freeze my game until the file isn't load no ?