Search Unity

Question Unable To hear Recorded Audio

Discussion in 'Audio & Video' started by AnthonyMir, Oct 25, 2021.

  1. AnthonyMir

    AnthonyMir

    Joined:
    Jul 10, 2021
    Posts:
    24
    I have an issue which i suspect is the encoding?
    When i record an audio Using the following Code Then I Send it to the backend / Then try to read it somewhere else I'm unable to hear it due to this Error:
    Cannot create FMOD::Sound Instance for clip ""(Fmod error:Unsupported file or audio format.)

    Please Note: the audio sent to the database can be heard Using the "url", But not in Unity
    Also, I tried Downloading an mp3 file and manually placing it in the database The audio can be heard...
    Also, After Recording the audio I can hear it, But i cannot after sending it to the database...

    so since i can hear it after recording and i can hear a manually uploaded clip i think the problem is in "saving" but i have no clue where or how,

    Please Help

    Microphone Code:
    Code (CSharp):
    1. using Newtonsoft.Json.Linq;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.IO;
    5. using System.Net.Http;
    6. using System.Net.Http.Headers;
    7. using System.Text;
    8. using System.Threading.Tasks;
    9. using UnityEditor;
    10. using UnityEngine;
    11. using Optimize;
    12. using attachment;
    13.  
    14. public class MicroPhone : Attachment<AudioClip>
    15. {
    16.     // Boolean flags shows if the microphone is connected
    17.     private bool micConnected = false;
    18.     //A handle to the attached AudioSource
    19.  
    20.     AudioClip getAudioClipRecorded;
    21.     [SerializeField]
    22.     MicrophoneUI getMicrophoneUI;
    23.    
    24.     public AudioClip Get_LastAudioRecorded { get { return getAudioClipRecorded ; } }
    25.  
    26.     void Start()
    27.     {
    28.         //Check if there is at least one microphone connected
    29.         if (Microphone.devices.Length <= 0)
    30.         {
    31.             //Throw a warning message at the console if there isn't
    32.             Debug.LogWarning("Microphone not connected!");
    33.         }
    34.         else //At least one microphone is present
    35.         {
    36.             //Set our flag 'micConnected' to true
    37.             micConnected = true;
    38.    
    39.         }
    40.     }
    41.     public void Start_Record()
    42.     {
    43.         if ( Check_ForMicrophone())
    44.         {
    45.             //Start recording and store the audio captured from the microphone at the AudioClip in the AudioSource
    46.             getAudioClipRecorded = Microphone.Start(null, false, 10, 44100);
    47.  
    48.             getMicrophoneUI.Start_Record();
    49.          
    50.         }
    51.     }
    52.     public void Stop_Record()
    53.     {
    54.         if (Check_ForMicrophone() && getAudioClipRecorded != null )
    55.         {
    56.             getAudioClipRecorded =  AudioClipOptimizer.Optimize_AudioClip(getAudioClipRecorded);
    57.             Save_Record();
    58.             Microphone.End(null); //Stop the audio recording
    59.             getAudioClipRecorded = null;
    60.             getMicrophoneUI.Stop_Record();
    61.         }
    62.     }
    63.  
    64.     public virtual void Save_Record()
    65.     {
    66.         string audioName = UnityEngine.Random.Range(0, 10000).ToString();
    67.         getAudioClipRecorded.name = audioName;
    68.         string thePath="";
    69.         if (getAudioClipRecorded != null) {
    70.          
    71.             thePath = SavWav.Save(OnServer.Instance.CurrentProjectLoaded.Name, audioName, getAudioClipRecorded , OnSelectedItem.Instance.CurrentIdClicked);
    72.         }
    73.  
    74.         if (thePath != "" && getAudioClipRecorded)
    75.         {
    76.             Upload_AttachmentSuccessfully(getAudioClipRecorded, thePath);
    77.         }
    78.  
    79.     }
    80.     public virtual void Delete_Wav(string name)
    81.     {
    82.         Remove_AttachmentSuccessfully(getAudioClipRecorded);
    83.         DeleteWav.Delete(OnServer.Instance.CurrentProjectLoaded.Name, name ,
    84.             getAudioClipRecorded , OnSelectedItem.Instance.CurrentIdClicked);
    85.     }
    86.    
    87.     public bool Check_ForMicrophone()
    88.     {
    89.         if (Microphone.devices.Length <= 0 && Microphone.IsRecording(null))
    90.         {
    91.             micConnected = false;
    92.         }
    93.         else  
    94.         {
    95.             micConnected = true;
    96.         }
    97.         getMicrophoneUI.Microphone_Connected(micConnected);
    98.         return micConnected;
    99.     }
    100.    
    101.  
    102.  
    103. }



    Save Code:

    Code (CSharp):
    1. using System;
    2. using System.IO;
    3. using UnityEngine;
    4. using System.Collections.Generic;
    5. using UnityEditor;
    6.  
    7. public static class SavWav
    8. {
    9.  
    10.     const string WavUrlSaved= "Assets/Resources/Recorded/"; // Recorded/ProjectName/ItemCurrentClicked/AudioClip
    11.     const int HEADER_SIZE = 44;
    12.  
    13.  
    14.     public static string Save(string projectName , string filename, AudioClip clip , string itemID)
    15.     {
    16.         if (!filename.ToLower().EndsWith(".mp3"))
    17.         {
    18.             filename += ".mp3";
    19.         }
    20.         var filepath2 = Path.Combine(WavUrlSaved, projectName);
    21.         var filepath0 = Path.Combine(filepath2, itemID);
    22.         var filepath = Path.Combine(filepath0, filename);
    23.  
    24.  
    25.         string pp = Path.Combine(Application.persistentDataPath, filename);
    26.         // Make sure directory exists if user is saving to sub dir.
    27.  
    28.         Directory.CreateDirectory(Path.GetDirectoryName(pp));
    29.  
    30.         using (var fileStream = CreateEmpty(pp))
    31.         {
    32.  
    33.             ConvertAndWrite(fileStream, clip);
    34.  
    35.             WriteHeader(fileStream, clip);
    36.         }
    37. #if(UNITY_EDITOR)
    38.         AssetDatabase.Refresh();
    39. #endif
    40.         return "file://"+pp; // TODO: return false if there's a failure saving the file
    41.     }
    42.  
    43.     public static AudioClip TrimSilence(AudioClip clip, float min)
    44.     {
    45.         var samples = new float[clip.samples];
    46.  
    47.         clip.GetData(samples, 0);
    48.  
    49.         return TrimSilence(new List<float>(samples), min, clip.channels, clip.frequency);
    50.     }
    51.  
    52.     public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz)
    53.     {
    54.         return TrimSilence(samples, min, channels, hz, false, false);
    55.     }
    56.  
    57.     public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream)
    58.     {
    59.         int i;
    60.  
    61.         for (i = 0; i < samples.Count; i++)
    62.         {
    63.             if (Mathf.Abs(samples[i]) > min)
    64.             {
    65.                 break;
    66.             }
    67.         }
    68.  
    69.         samples.RemoveRange(0, i);
    70.  
    71.         for (i = samples.Count - 1; i > 0; i--)
    72.         {
    73.             if (Mathf.Abs(samples[i]) > min)
    74.             {
    75.                 break;
    76.             }
    77.         }
    78.  
    79.         samples.RemoveRange(i, samples.Count - i);
    80.  
    81.         var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);
    82.  
    83.         clip.SetData(samples.ToArray(), 0);
    84.  
    85.         return clip;
    86.     }
    87.  
    88.     static FileStream CreateEmpty(string filepath)
    89.     {
    90.         Debug.Log("*** Create Empty "+filepath);
    91.         var fileStream = new FileStream(filepath, FileMode.Create);
    92.         byte emptyByte = new byte();
    93.  
    94.         for (int i = 0; i < HEADER_SIZE; i++) //preparing the header
    95.         {
    96.             fileStream.WriteByte(emptyByte);
    97.         }
    98.  
    99.         return fileStream;
    100.     }
    101.  
    102.     static void ConvertAndWrite(FileStream fileStream, AudioClip clip)
    103.     {
    104.  
    105.         var samples = new float[clip.samples];
    106.  
    107.         clip.GetData(samples, 0);
    108.  
    109.         Int16[] intData = new Int16[samples.Length];
    110.         //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]
    111.  
    112.         Byte[] bytesData = new Byte[samples.Length * 2];
    113.         //bytesData array is twice the size of
    114.         //dataSource array because a float converted in Int16 is 2 bytes.
    115.  
    116.         int rescaleFactor = 32767; //to convert float to Int16
    117.  
    118.         for (int i = 0; i < samples.Length; i++)
    119.         {
    120.             intData[i] = (short)(samples[i] * rescaleFactor);
    121.             Byte[] byteArr = new Byte[2];
    122.             byteArr = BitConverter.GetBytes(intData[i]);
    123.             byteArr.CopyTo(bytesData, i * 2);
    124.         }
    125.  
    126.         fileStream.Write(bytesData, 0, bytesData.Length);
    127.     }
    128.  
    129.     static void WriteHeader(FileStream fileStream, AudioClip clip)
    130.     {
    131.  
    132.         var hz = clip.frequency;
    133.         var channels = clip.channels;
    134.         var samples = clip.samples;
    135.  
    136.         fileStream.Seek(0, SeekOrigin.Begin);
    137.  
    138.         Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
    139.         fileStream.Write(riff, 0, 4);
    140.  
    141.         Byte[] chunkSize = BitConverter.GetBytes(fileStream.Length - 8);
    142.         fileStream.Write(chunkSize, 0, 4);
    143.  
    144.         Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
    145.         fileStream.Write(wave, 0, 4);
    146.  
    147.         Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
    148.         fileStream.Write(fmt, 0, 4);
    149.  
    150.         Byte[] subChunk1 = BitConverter.GetBytes(16);
    151.         fileStream.Write(subChunk1, 0, 4);
    152.  
    153.         UInt16 two = 2;
    154.         UInt16 one = 1;
    155.  
    156.         Byte[] audioFormat = BitConverter.GetBytes(one);
    157.         fileStream.Write(audioFormat, 0, 2);
    158.  
    159.         Byte[] numChannels = BitConverter.GetBytes(channels);
    160.         fileStream.Write(numChannels, 0, 2);
    161.  
    162.         Byte[] sampleRate = BitConverter.GetBytes(hz);
    163.         fileStream.Write(sampleRate, 0, 4);
    164.  
    165.         Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2
    166.         fileStream.Write(byteRate, 0, 4);
    167.  
    168.         UInt16 blockAlign = (ushort)(channels * 2);
    169.         fileStream.Write(BitConverter.GetBytes(blockAlign), 0, 2);
    170.  
    171.         UInt16 bps = 16;
    172.         Byte[] bitsPerSample = BitConverter.GetBytes(bps);
    173.         fileStream.Write(bitsPerSample, 0, 2);
    174.  
    175.         Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
    176.         fileStream.Write(datastring, 0, 4);
    177.  
    178.         Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
    179.         fileStream.Write(subChunk2, 0, 4);
    180.  
    181.         //        fileStream.Close();
    182.     }
    183. }
    184. public static class DeleteWav
    185. {
    186. const string WavUrlSaved = "Assets/Resources/Recorded/";
    187.     public static bool Delete(string projectName, string filename, AudioClip clip,string itemID)
    188.     {
    189.    
    190.         var filepath2 = Path.Combine(WavUrlSaved, projectName);
    191.         var filepath0 = Path.Combine(filepath2, itemID);
    192.         var filepath = Path.Combine(filepath0, filename);
    193.         string pp = Path.Combine(Application.persistentDataPath, filename);
    194.  
    195.         filename = Path.Combine(filepath  + ".mp3");//Assets/Resources/Recorded/A-Tech Model.ifc\5628
    196.  
    197.         File.Delete(pp);
    198.  
    199.         //File.Delete(filename);
    200.  
    201. #if (UNITY_EDITOR)
    202.         AssetDatabase.Refresh();
    203. #endif
    204.         return true; // TODO: return false if there's a failure saving the file
    205.    
    206.     }
    207.    
    208. }