Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Playing multiple audio files simultaneously from an EditorWindow script

Discussion in 'Editor & General Support' started by Ruchmair, Mar 9, 2021.

  1. Ruchmair

    Ruchmair

    Joined:
    Sep 20, 2015
    Posts:
    544
    Hi,

    I have been able to play audio files in the Editor for many years now but never able to play multiple aufio files simultaneously.

    I use two methods to play Audio files.

    Method 1 : Use reflection to access the AudioUitl class and call PlayClip or PlayPreviewClip depending o the unity version . This can only be run from the main thread.

    Code (CSharp):
    1.         public static void PlayClip(AudioClip clip, float startTime, bool loop)
    2.         {
    3.             var startSample = (int)(startTime * clip.frequency);
    4.  
    5.             var assembly = typeof(AudioImporter).Assembly;
    6.             var audioUtilType = assembly.GetType("UnityEditor.AudioUtil");
    7.  
    8.             Type[] typeParams = { typeof(AudioClip), typeof(int), typeof(bool) };
    9.             object[] objParams = { clip, startSample, loop };
    10.             MethodInfo method = null;
    11.              if (audioUtilType.GetMethod("PlayClip", typeParams) != null)
    12.               method =  audioUtilType.GetMethod("PlayClip", typeParams);
    13.              else
    14.              method = audioUtilType.GetMethod("PlayPreviewClip", typeParams);
    15.             method.Invoke(null, BindingFlags.Static | BindingFlags.Public, null, objParams,
    16.                 null);
    17.  
    18.          
    19.         }

    Method 2 : calling SoundPlayer.Play(); this can be call from a new thread but will not allow for multiple SoundPlayer.Play() functions to run simultaneously.

    Code (CSharp):
    1. System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer()
    2. myPlayer.SoundLocation =PathToWAVFile
    3. myPlayer.Play();

    I notice that the Unity Timeline does play multiple clips at once , I would really love to know how i could also play multiple clips simultaneously.

    Or does the Unity timeline combine all the audio into one in the background and just play a single file ?