Skip to content

Instantly share code, notes, and snippets.

@readpan
Created May 12, 2023 02:51
Show Gist options
  • Save readpan/a7b43c40342f315a32146cbad0d36cfe to your computer and use it in GitHub Desktop.
Save readpan/a7b43c40342f315a32146cbad0d36cfe to your computer and use it in GitHub Desktop.
Base64 string convert to ogg file, play as AudioClip in Unity
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace DefaultNamespace.Scripts
{
public static class AudioPlayer
{
static async Task<AudioClip> GetAudioClip(string b64Str)
{
var fileBytes = Convert.FromBase64String(b64Str);
var fullPath = Application.persistentDataPath + "/temp.ogg";
await File.WriteAllBytesAsync(fullPath, fileBytes);
fullPath = "file://" + fullPath;
using (var uwr = UnityWebRequestMultimedia.GetAudioClip(fullPath, AudioType.MPEG))
{
uwr.downloadHandler = new DownloadHandlerAudioClip(fullPath, AudioType.OGGVORBIS);
((DownloadHandlerAudioClip)uwr.downloadHandler).streamAudio = true;
uwr.SendWebRequest();
while (!uwr.isDone)
await Task.Delay(1); //can replace with UniTask.WaitUntil(() => uwr.isDone);
File.Delete(fullPath);
return (uwr.downloadHandler as DownloadHandlerAudioClip)?.audioClip;
}
}
private static Dictionary<string, AudioClip> _audioClips = new Dictionary<string, AudioClip>();
public static async void PlayOgg(string audioName, string base64)
{
if (_audioClips.TryGetValue(audioName, out var clip))
{
AudioSource.PlayClipAtPoint(clip, Vector3.zero);
return;
}
var audioClip = await GetAudioClip(base64);
_audioClips.Add(audioName, audioClip);
AudioSource.PlayClipAtPoint(audioClip, Vector3.zero);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment