Search Unity

Audio UnityWebRequest

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

  1. AnthonyMir

    AnthonyMir

    Joined:
    Jul 10, 2021
    Posts:
    24
    I'm getting the following ERROR on Line 8:
    Error: Cannot create FMOD::Sound instance for clip "" (FMOD error: Unsupported file or audio format. )
    The file is an mp3 and i'm unable to fix this issue

    The url is Https://Example.com/something/hello/Project21/2980.mp3

    Code (CSharp):
    1.  
    2. WWW www = new WWW(url);
    3. yield return www;
    4.  
    5. GameObject audio = Instantiate(imagePrefab) as GameObject;
    6. audio.GetComponent<Image>().sprite = spriteAudio;
    7.  
    8. audio.GetComponent<AudioSource>().clip = www.GetAudioClip(false, true, AudioType.MPEG);
    9.  
    10. audio.GetComponent<Button>().onClick.AddListener(delegate { audio.GetComponent<AudioSource>().Play(); });
    11. audio.transform.SetParent(content.transform, false);
    I Have also tried the following but i'm getting the same Error on Line 13

    Code (CSharp):
    1.  
    2. using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG))
    3. {
    4. yield return www.SendWebRequest();
    5.  
    6. if (www.result == UnityWebRequest.Result.ConnectionError)
    7. {
    8. Debug.Log(www.error);
    9. }
    10. else
    11. {
    12.  
    13.  AudioClip myClip = DownloadHandlerAudioClip.GetContent(www);
    14.  
    15. GameObject audio = Instantiate(imagePrefab) as GameObject;
    16. audio.GetComponent<Image>().sprite = spriteAudio;
    17. audio.GetComponent<AudioSource>().clip = myClip;
    18. audio.GetComponent<Button>().onClick.AddListener(delegate { audio.GetComponent<AudioSource>().Play(); });
    19. audio.transform.SetParent(content.transform, false);
    20. }
    21. }

    Save Script
    Code (CSharp):
    1. sing 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. }
     
    Last edited: Oct 25, 2021
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,497
    FYI: There's a dedicated Audio sub-forum listed on the forum page here.
     
  3. AnthonyMir

    AnthonyMir

    Joined:
    Jul 10, 2021
    Posts:
    24
    should i move my post ?
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,497
    Done!
     
  5. AnthonyMir

    AnthonyMir

    Joined:
    Jul 10, 2021
    Posts:
    24
    Help
     
  6. r618

    r618

    Joined:
    Jan 19, 2009
    Posts:
    1,305
    your URL is 404
     
  7. AnthonyMir

    AnthonyMir

    Joined:
    Jul 10, 2021
    Posts:
    24
    No my url is perfectly Normal (the one provided is an Example) i can hear the audio in the url by accessing it but i cannot in unity
     
  8. Well, what happens if you download it and import it into Unity on the regular way? Maybe it isn't a supported format?
     
    AnthonyMir likes this.
  9. AnthonyMir

    AnthonyMir

    Joined:
    Jul 10, 2021
    Posts:
    24
    I think the problem is when i "save it"
    Because after recording the audio i am able to hear it (its Mp3)
    Also if i manually put an mp3 file on the database i'm also able to retrieve it and hear it

    But i'm unable to hear the ones that i record after saving them and sending them to the database even tho i can see them on the database and i can hear it there

    Could it be some encoding problem?

    Note: I have provided the save script in the main post
     
  10. You can check the headers too (when download it through the www object), like content type and stuff like that. I haven't configured web server in ages, so I do not remember the exact settings and headers, you can research it on the web under like "serving mp3 files on web" or something.