[SOLVED] Use Base 64 Audio as asset

Hello Fellow developers!

Was wondering if it was possible, to load a base64 encoded Audio File (“data:audio/mpeg;base64,SUQzBA…”) as an asset to add as a slot which then can be played back.

I have tried the following (fllowing this example Examp):

    var t = new pc.Sound(new Audio("data:audio/mpeg;base64,SUQzBA....."));
    asset = new pc.Asset("myAudioAsset-"+this.audioFileCount, "audio",{
       url: ""
    );
    
    asset.resource = t;
    asset.loaded = true;

    this.app.assets.add(asset);

It then creates an Asset with the following properties:

If i then try to add it to a slot and play it, it doesn’t work.

Any help is much appreciated!

Hi @Bfischlin,

This is definitely doable, tohough I haven’t done it before. We need to find out the exact structure/object a pc.Asset of audio type expects.

Checking the structure of an .mp3 asset loaded:

image

So I think instead of creating a pc.Sound object and assigning it as the asset resource, maybe just assign the AudioBuffer loaded directly.

1 Like

Thank you for your replay @Leonidas !

That’s exactly what my next thought was :slight_smile:

I was able to get it to work now!

    var base64 = "data:audio/mpeg;base64,SUQzBA.....";
    var options = {retry: false};
    options.responseType = "arraybuffer";
    
    var audioContext = new AudioContext();
    
    pc.http.get(base64, options, function(err, response) {
        if (err) {
          console.log(err);
          return;
        }
        audioContext.decodeAudioData(response, function(buffer) {
             var soundComp = new pc.Sound(audioBuffer);
             asset = new pc.Asset("myAudioAsset-"+this.audioFileCount, "audio", null, base64);
             asset.resource = soundComp;
             asset.loaded = true;
             this.app.assets.add(asset);
        }.bind(this),
        function(e) {
            console.error("error decoding audio data" + e.err);
        }.bind(this));
    }.bind(this));

I can then add the a Slot with that Asset and play it!

1 Like

That’s great!

Thanks for sharing your working solution @Bfischlin, much appreciated.