For various reasons, I need to be able create an audio clip from a byte containing ogg/vorbis (desktop) or mp3 (mobile) data.
Currently the only viable options I can see are using external decoders (such as NVorbis)… Which seems insane to me.
I don’t need to stream the data, it’s a load it all scenario. Encoded playback would be preferred, but i don’t mind if i have to decode to PCM (which is what i’ll have to deal with with NVorbis).
Any easier way to do this?
iv7
April 17, 2015, 11:57am
3
Way with handmade web server.
using UnityEngine;
using System.Collections;
using System.Net;
using System;
using System.IO;
public class Main : MonoBehaviour
{
HttpListener _listener;
string url = "http://127.0.0.1:8080/";
IEnumerator Start()
{
_listener = new HttpListener();
_listener.Prefixes.Add( url );
_listener.Start();
_listener.BeginGetContext(new AsyncCallback(ListenerCallback),_listener);
WWW www = new WWW( url );
yield return www;
AudioSource AS = GetComponent<AudioSource>();
AS.clip = www.GetAudioClip( true, true, AudioType.MPEG );
AS.Play();
}
private void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener) result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
byte[] buffer = File.ReadAllBytes( "1.mp3" );
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write( buffer, 0, buffer.Length );
output.Close();
//_listener.BeginGetContext(new AsyncCallback(ListenerCallback),_listener);
_listener.Close();
}
}
If you dont mind caching to disk, this should work for mp3s (I don’t know about oggs)
byte[] rawData = byte[];
string tempFile = Application.persistentDataPath + "/bytes.mp3";
System.IO.File.WriteAllBytes(tempFile, rawData);
WWW loader = new WWW("file://" + tempFile);
yield return loader;
if(!System.String.IsNullOrEmpty(loader.error))
Debug.LogError(loader.error);
AudioClip s1 = loader.GetAudioClip(false, false, AudioType.MPEG);
//or
AudioClip s2 = loader.audioClip;