PouchDB load m4a attachment into HTML5 player

40 Views Asked by At

I have a very simple application I am making that needs to load 30 second m4a files from a couch server. I am able to receive the files but can not get them to load in a player. The files are uploaded through Fauxton and have been deleted and reuploaded to be sure the issue was not in the upload.

I have also loaded the object url into a link and tried to download the file which can not be played.

I have tried both using the source directly in the audio tag as well as adding the source tag.

I have tested the files in the audio player and they work fine locally.

I think I there is something wrong with the way I am creating the blob or url.

<audio controls id="mediaPlayer"></audio>

var db = new PouchDB('http://user:password@localhost:5984/music');
  db.get('9d3f17d01be8283c461eaa01940329b4', { attachments:true } ).then(function (doc){
    // Load first file
    var media = Object.values(doc._attachments)[0];
    // Get Player
    var player = document.getElementById('mediaPlayer');
    // Create blob from data - media content type is 
    var blob = new Blob([ media.data ], { type: media.content_type });
    // Create url from blob
    var afile = URL.createObjectURL(blob);
    // Set source and load
    player.src = afile;
    player.load();
  });
1

There are 1 best solutions below

0
James On

I solved my own issue. This was a complete oversight on my end. Fauxton uploads all attachments as Base64 not blobs. I had to simply decode the data before converting it to a blob. I am using node so I used buffer to decode the string before creating the blob.

If you are using raw vanilla js you should be able to use atob(media.data) in place of the buffer, but I did not test it.

import { Buffer } from 'buffer';

var db = new PouchDB('http://user:password@localhost:5984/music');
db.get('9d3f17d01be8283c461eaa01940329b4', { attachments:true } ).then(function (doc){
    // Load first file
    var media = Object.values(doc._attachments)[0];
    // Get Player
    var player = document.getElementById('mediaPlayer');
    // Remove Encoding
    var raw = Buffer.from(media.data, 'base64');
    // Create blob from data
    var blob = new Blob([ raw ], { type: media.content_type });
    // Create url from blob
    var afile = URL.createObjectURL(blob);
    // Set source and load
    player.src = afile;
    player.load();
});