Search Unity

Audio Using NAudio to create AudioClip in Unity, freezes 1-2 seconds while reading data

Discussion in 'Audio & Video' started by JamieD64, Nov 23, 2018.

  1. JamieD64

    JamieD64

    Joined:
    Mar 13, 2018
    Posts:
    5
    Hello, I was wondering if someone could assist with the issues I am having. I am currently using the below code in my Unity project to stream mp3 files from a directory. It works great however, it freezes while the file is read in and the float is filled. As this project is in VR the freezes are very jarring. How can I resolve it so that it can read in without the lockup? Do I try and put it on another thread?

    When commenting out the below lines there are no hitches.

    aud = new AudioFileReader(musicPath);

    aud.Read(AudioData, 0, (int)aud.Length);

    Code (CSharp):
    1.  public void LoadSong(string musicPath){
    2.  
    3.     //Set title of song
    4.     songTitle = Path.GetFileNameWithoutExtension(musicPath);
    5.     if(songTitle != currentlyPlaying && songTitle !=
    6. lastPlayedTitle){
    7.         //Parse the file with NAudio
    8.         aud = new AudioFileReader(musicPath);
    9.  
    10.         //Create an empty float to fill with song data
    11.         AudioData = new float[aud.Length];
    12.         //Read the file and fill the float
    13.         aud.Read(AudioData, 0, (int)aud.Length);
    14.  
    15.         //Create a clip file the size needed to collect the sound data
    16.         craftClip = AudioClip.Create(songTitle, (int)aud.Length, aud.WaveFormat.Channels, aud.WaveFormat.SampleRate, false);
    17.         //Fill the file with the sound data
    18.         craftClip.SetData(AudioData, 0);
    19.  
    20.         if(craftClip.isReadyToPlay){
    21.             playMusic(craftClip, songTitle);
    22.             aud.Dispose();
    23.          }
    24.  
    25.         }
    26.  
    27.         else
    28.         {
    29.             playMusic(lastPlayedAudioFile, lastPlayedTitle);
    30.         }
    31.  
    32. }
    I have managed to improve the situation slightly by storing the last played song so that if the user selects the previous song that was played there is no delay.

    Many thanks


     
  2. JamieD64

    JamieD64

    Joined:
    Mar 13, 2018
    Posts:
    5