Last active
August 8, 2022 11:59
-
-
Save allfake/861b446d4108340861f76488307d37fc to your computer and use it in GitHub Desktop.
Best way to load audio (ogg) from file(byte[]) in UNITY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
USE NVorbis | |
https://github.com/NVorbis/NVorbis | |
https://forum.unity.com/threads/ogg-byte-to-audioclip.1004843/ | |
Why? When use webgl and you want to load data from IndexedDB. [File.ReadAllBytes()] | |
UnityWebRequestMultimedia.GetAudioClip Request will not work. (Load direct file from Native iOS and android or PC is OK) | |
People will say that you should use assetbundle or steaming asset. | |
But i want to download DIRECT FILE FROM INTERNET and save for cache (self cache). | |
Why i don't use assetbundle? Because i don't want to build asset for EACH platfrom. (switch target is pain) | |
With direct download give you have only one file for all platfrom. (iOS, Android, Webg, ...) | |
For model and a lot of other things Assetbundle is good way to do. | |
But for this time, the game i make that have things contain only 2D spite. | |
It more like app than game, that why i made this way. | |
NVorbis for me is easy way to do so. | |
I got this from unity forum. Work like a magic but have spike on load. | |
Also beware of memory! (4 minute song take aroud 20MB... that a lot on mobile) | |
How to. | |
Copy NVorbis to your folder | |
var sampleData = YOUR_BYTES_ARRAY | |
using (var vorbis = new NVorbis.VorbisReader( new MemoryStream( sampleData, false ) ) ) | |
{ | |
if (Debug.isDebugBuild) | |
{ | |
Debug.Log( | |
$"Found ogg ch={vorbis.Channels} freq={vorbis.SampleRate} samp={vorbis.TotalSamples}"); | |
} | |
var audioBuffer = new float[vorbis.TotalSamples]; // Just dump everything | |
var audioClip = AudioClip.Create(filename, (int)(vorbis.TotalSamples / vorbis.Channels), vorbis.Channels, vorbis.SampleRate, false); | |
int read = vorbis.ReadSamples( _audioBuffer, 0, (int)vorbis.TotalSamples ); | |
audioClip.SetData( audioBuffer, 0 ); // <-- your clip Remember to destroy when not use anymore | |
} | |
The end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment