Audio UnityWebRequest

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

WWW www = new WWW(url);
yield return www;

GameObject audio = Instantiate(imagePrefab) as GameObject;
audio.GetComponent<Image>().sprite = spriteAudio;

audio.GetComponent<AudioSource>().clip = www.GetAudioClip(false, true, AudioType.MPEG);

audio.GetComponent<Button>().onClick.AddListener(delegate { audio.GetComponent<AudioSource>().Play(); });
audio.transform.SetParent(content.transform, false);

I Have also tried the following but i’m getting the same Error on Line 13

using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG))
{
yield return www.SendWebRequest();

if (www.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(www.error);
}
else
{

 AudioClip myClip = DownloadHandlerAudioClip.GetContent(www);

GameObject audio = Instantiate(imagePrefab) as GameObject;
audio.GetComponent<Image>().sprite = spriteAudio;
audio.GetComponent<AudioSource>().clip = myClip;
audio.GetComponent<Button>().onClick.AddListener(delegate { audio.GetComponent<AudioSource>().Play(); });
audio.transform.SetParent(content.transform, false);
}
}

Save Script

sing System;
using System.IO;
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;

public static class SavWav
{

    const string WavUrlSaved= "Assets/Resources/Recorded/"; // Recorded/ProjectName/ItemCurrentClicked/AudioClip
    const int HEADER_SIZE = 44;


    public static string Save(string projectName , string filename, AudioClip clip , string itemID)
    {
        if (!filename.ToLower().EndsWith(".mp3"))
        {
            filename += ".mp3";
        }
        var filepath2 = Path.Combine(WavUrlSaved, projectName);
        var filepath0 = Path.Combine(filepath2, itemID);
        var filepath = Path.Combine(filepath0, filename);


        string pp = Path.Combine(Application.persistentDataPath, filename);
        // Make sure directory exists if user is saving to sub dir.

        Directory.CreateDirectory(Path.GetDirectoryName(pp));

        using (var fileStream = CreateEmpty(pp))
        {

            ConvertAndWrite(fileStream, clip);

            WriteHeader(fileStream, clip);
        }
#if(UNITY_EDITOR)
        AssetDatabase.Refresh();
#endif
        return "file://"+pp; // TODO: return false if there's a failure saving the file
    }

    public static AudioClip TrimSilence(AudioClip clip, float min)
    {
        var samples = new float[clip.samples];

        clip.GetData(samples, 0);

        return TrimSilence(new List<float>(samples), min, clip.channels, clip.frequency);
    }

    public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz)
    {
        return TrimSilence(samples, min, channels, hz, false, false);
    }

    public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream)
    {
        int i;

        for (i = 0; i < samples.Count; i++)
        {
            if (Mathf.Abs(samples[i]) > min)
            {
                break;
            }
        }

        samples.RemoveRange(0, i);

        for (i = samples.Count - 1; i > 0; i--)
        {
            if (Mathf.Abs(samples[i]) > min)
            {
                break;
            }
        }

        samples.RemoveRange(i, samples.Count - i);

        var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);

        clip.SetData(samples.ToArray(), 0);

        return clip;
    }

    static FileStream CreateEmpty(string filepath)
    {
        Debug.Log("*** Create Empty "+filepath);
        var fileStream = new FileStream(filepath, FileMode.Create);
        byte emptyByte = new byte();

        for (int i = 0; i < HEADER_SIZE; i++) //preparing the header
        {
            fileStream.WriteByte(emptyByte);
        }

        return fileStream;
    }

    static void ConvertAndWrite(FileStream fileStream, AudioClip clip)
    {

        var samples = new float[clip.samples];

        clip.GetData(samples, 0);

        Int16[] intData = new Int16[samples.Length];
        //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]

        Byte[] bytesData = new Byte[samples.Length * 2];
        //bytesData array is twice the size of
        //dataSource array because a float converted in Int16 is 2 bytes.

        int rescaleFactor = 32767; //to convert float to Int16

        for (int i = 0; i < samples.Length; i++)
        {
            intData[i] = (short)(samples[i] * rescaleFactor);
            Byte[] byteArr = new Byte[2];
            byteArr = BitConverter.GetBytes(intData[i]);
            byteArr.CopyTo(bytesData, i * 2);
        }

        fileStream.Write(bytesData, 0, bytesData.Length);
    }

    static void WriteHeader(FileStream fileStream, AudioClip clip)
    {

        var hz = clip.frequency;
        var channels = clip.channels;
        var samples = clip.samples;

        fileStream.Seek(0, SeekOrigin.Begin);

        Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
        fileStream.Write(riff, 0, 4);

        Byte[] chunkSize = BitConverter.GetBytes(fileStream.Length - 8);
        fileStream.Write(chunkSize, 0, 4);

        Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
        fileStream.Write(wave, 0, 4);

        Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
        fileStream.Write(fmt, 0, 4);

        Byte[] subChunk1 = BitConverter.GetBytes(16);
        fileStream.Write(subChunk1, 0, 4);

        UInt16 two = 2;
        UInt16 one = 1;

        Byte[] audioFormat = BitConverter.GetBytes(one);
        fileStream.Write(audioFormat, 0, 2);

        Byte[] numChannels = BitConverter.GetBytes(channels);
        fileStream.Write(numChannels, 0, 2);

        Byte[] sampleRate = BitConverter.GetBytes(hz);
        fileStream.Write(sampleRate, 0, 4);

        Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2
        fileStream.Write(byteRate, 0, 4);

        UInt16 blockAlign = (ushort)(channels * 2);
        fileStream.Write(BitConverter.GetBytes(blockAlign), 0, 2);

        UInt16 bps = 16;
        Byte[] bitsPerSample = BitConverter.GetBytes(bps);
        fileStream.Write(bitsPerSample, 0, 2);

        Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
        fileStream.Write(datastring, 0, 4);

        Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
        fileStream.Write(subChunk2, 0, 4);

        //        fileStream.Close();
    }
}
public static class DeleteWav
{
const string WavUrlSaved = "Assets/Resources/Recorded/";
    public static bool Delete(string projectName, string filename, AudioClip clip,string itemID)
    {
    
        var filepath2 = Path.Combine(WavUrlSaved, projectName);
        var filepath0 = Path.Combine(filepath2, itemID);
        var filepath = Path.Combine(filepath0, filename);
        string pp = Path.Combine(Application.persistentDataPath, filename);

        filename = Path.Combine(filepath  + ".mp3");//Assets/Resources/Recorded/A-Tech Model.ifc\5628

        File.Delete(pp);

        //File.Delete(filename);

#if (UNITY_EDITOR)
        AssetDatabase.Refresh();
#endif
        return true; // TODO: return false if there's a failure saving the file
   
    }
    
}

FYI: There’s a dedicated Audio sub-forum listed on the forum page here.

should i move my post ?

Done!

Help

your URL is 404

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

Well, what happens if you download it and import it into Unity on the regular way? Maybe it isn’t a supported format?

1 Like

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

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.