AudioClip.Length is incorrect when loading from WebRequest GetAudioClip

I think this is a potential bug to report, but I want to sanity check that I am not doing anything wrong first.

I have a bunch of mp3 files in the StreamingAssets folder (trying to keep the build size down for Android).

When I load them via:

var webRequest = UnityWebRequestMultimedia.GetAudioClip(fileUrl, AudioType.MPEG);
            yield return webRequest.SendWebRequest();

The clip length is 2x the actual length.

When I put them in Resources and load via:

 var clip = Resources.Load<AudioClip>(fileUrl.Substring(0, fileUrl.Length-4));

The clip length is correct.

Iā€™ve tried AudioType.MPEG and AudioType.UNKNOWN.

Iā€™ve tried to sequence these audio clips by either checking clip.length and waiting that amount of time or by checking AudioSource.IsPlaying but even the IsPlaying returns true for the double amount.

Sooooo. Is this a bug? Should I be using a different method here either for loading or for storing?

Iā€™ve attached a zip file of the mp3 in case the compression/etc isnā€™t supported. It comes up as Vorbis under Unityā€™s compression format.

6975179ā€“822599ā€“2_VisualMemory.zip (42.2 KB)

1 Like

I also face same issue.
I try to download audioclip via UnityWebRequestMultimedia.GetAudioClip
The result of AudioClip.samples and AudioClip.length are twice than those that I expected.

It seems that this behaviour is WebRequest Bug.

 public static async UniTask<AudioClip> GetAudioClipFromWWW(string uri, CancellationToken token = default)
        {
            AudioType type = AudioType.WAV;
            if (uri.Contains(".ogg"))
            {
                type = AudioType.OGGVORBIS;
            }
            else if (uri.Contains(".mp3"))
            {
                type = AudioType.MPEG;
            }

            using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(uri, type))
            {
                await www.SendWebRequest();
                if (www.isNetworkError || www.isHttpError )
                {
                    Debug.Log(www.error);
                    return null;
                }
                else
                {
                    AudioClip myClip = DownloadHandlerAudioClip.GetContent(www);
                    Debug.Log(
                        $"[Audio] ClipData Fs:{myClip.frequency}[Hz], {myClip.channels}[ch] Sample:{myClip.samples}, Len:{myClip.length}");
                    return myClip;
                }
            }
          
        }

This bug can be reproduced Unity2019.4.9f1 and Unity2018.4.22f1

Hey folks,

Weā€™d suggest making a bug report on this issue so the team can begin the process of looking into this for you :slight_smile: Let me know the bug report ID so I can flag internally.

@UnityMaru

Iā€™ve already made bug report on 30th, March

https://fogbugz.unity3d.com/default.asp?1325580_5kivb2tvs9o64e4q

Iā€™m afraid that title was too long to view, it may be cutoutā€¦
and There are still no action on this bug reportā€¦

Same Issue on 2020.3.15f2 and 2020.3.16f1.

Iā€™m seeing lenth = zero in 2021.3.0f1

same in 2020.3.30f1

This bug is still active and its fun to deal with. I had to go back into the project and update some audio files. Seems as though the updated files are not double length but the old ones are and Iā€™m not sure what is difference as the frequency/channels are the same. Bitrate on the mp3 files are different so that could be something to do with it? Just not sure how to catch that on the unity side as all properties seem to be the same.

for me in 2021.2.3f1 the length seems to be roughly 1/3rd of the source file

The result of AudioClip.samples and AudioClip.length are twice than those that I expected.

I am facing this issue still in 2022.3.2f1.

You can find a test project here: GitHub - achimmihca/UnityAudioClipMp3WrongDuration: Test loading AudioClip in Unity at runtime. Some mp3 files return a wrong duration.

Will open a new bug report.
Underwhelming as usual.

1 Like

Just discovered this bug in 2022.3.4f1

The generated audioclip Lenght and Samples value is always 0 on the WebGL build

Will open a new bug report.

Unity just confirmed the bug (IN-47586). Hopefully they will fix it in a future release.

I recently fixed this bug, it should makes it way soon in the latest and LTS versions.

It was a fun weird ass codec bugā€¦

Cheers!

2 Likes

You are a savior. I had fixed this manually, but I faced another issue.

public IEnumerator GetAudioClipUniversal(string fullPath, float percentageOffset, bool isLooping, bool playImmediately)
    {
        using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip($"file://{fullPath}", AudioType.MPEG))
        {
            yield return www.SendWebRequest();

            if (www.error == null)
            {
                UnloadMainSong();
                song = DownloadHandlerAudioClip.GetContent(www);
                int channels = song.channels;
                int frequency = song.frequency;
                float[] allSamples = new float[song.samples * channels];
                song.GetData(allSamples, 0);
                song.UnloadAudioData();

                // Audio clip is downloaded with a lot of leading zeros, we remove them manually...
                int lastIndex = Array.FindLastIndex(allSamples, b => b != 0);
                song = AudioClip.Create("song2", (lastIndex + 1) / channels, channels, frequency, false);
                song.SetData(allSamples[0..lastIndex], 0);

Turns out creating float[ ] array = new float creates ā€œEmpty fragmented heap spaceā€ that does not free up. So every time I load a song, around 100Mb of RAM is lost, after a handful song loads I run out of RAM and app crashesā€¦ Iā€™ll take a break and wait for the update to roll out.

Were you able to fix it? I came to the conclusion that the problem is in the audio files themselves. But of course, Unity also does not work correctly.

I had a similar issue using MP3 files, but it turns out that it was caused by using a variable bitrate encoding. Re-encoding using a constant bitrate fixed the issue. I know this is mentioned in other threads on this forum, but just posting here in case anyone else finds this thread looking for answers with the same issue I had.

I managed to find a workaround to this bug. I had the issue where the end of my .mp3 file was being cut off by ā€˜UnityWebRequestMultimedia.GetAudioClip(mp3audioPath, AudioType.MPEG)ā€™

Using the more primitive method from this forum post worked for me: How to load MP3 file into an AudioClip and make it stay compressed in memory?

Hereā€™s a code example of the solution. In GetMp3Audio I pass it the data for the mp3 then I load it and I can confirm it plays the entire mp3 correctly.

{
string filePath = System.IO.Path.Combine(Application.persistentDataPath, "output.mp3");
System.IO.File.WriteAllBytes(filePath, mp3Audio);
var path = "file:///" + Application.persistentDataPath + "/output.mp3";
StartCoroutine(PlayDownloadedAudio(path)); 
}

private IEnumerator PlayDownloadedAudio(string mp3audioPath)
{
var dh = new DownloadHandlerAudioClip(mp3audioPath, AudioType.MPEG);
dh.compressed = true;
using (UnityWebRequest wr = new UnityWebRequest(mp3audioPath, "GET", dh, null))
{
yield return wr.SendWebRequest();
if (wr.responseCode == 200)
{
PlayClip(dh.audioClip);
}
else
{
Debug.LogError("Error");
}
}
}```

I was stuck on this for hours, so hoping it helps someone :) P.S. If you use Play.HT this is the solution you should use after downloading their audio.

Using 2022.1.23f1
1 Like

Iā€™m still seeing this behaviour in 2023.1.3f1. Which version did the fix go live in? Thanks :slight_smile:

From what I see it has landed in a yet unreleased version (2023.2.xyz) and backports have not started yet. I implore your patience, as it should be available Soonā„¢.