Play MP3 Files in mobile App using JavaScript


#1

function Sound(source,volume,loop)
{
    this.source=source;
    this.volume=volume;
    this.loop=loop;
    var son;
    this.son=son;
    this.finish=false;
    this.stop=function()
    {
        document.body.removeChild(this.son);
    }
    this.start=function()
    {
        if(this.finish)return false;
        this.son=document.createElement("embed");
        this.son.setAttribute("src",this.source);
        this.son.setAttribute("hidden","true");
        this.son.setAttribute("volume",this.volume);
        this.son.setAttribute("autostart","true");
        this.son.setAttribute("loop",this.loop);
        document.body.appendChild(this.son);
    }
    this.remove=function()
    {
        document.body.removeChild(this.son);
        this.finish=true;
    }
    this.init=function(volume,loop)
    {
        this.finish=false;
        this.volume=volume;
        this.loop=loop;
    }
}

var foo=new Sound("URL",100,true);
foo.start();
foo.stop();
foo.start();
foo.init(100,false);
foo.remove();

#2

Do you have a question regarding this code?


#3

In case the question is why this isn't working, that's because embed doesn't implement the HTMLMediaElement interface, and there's no .autostart property (or attribute for that matter). If there was, it wouldn't even be necessary to append it to the DOM -- it would start playing right away.

Anyway you can actually just as well use an Audio element directly, or maybe write a simple factory to initialise it with some options:

var createAudio = function (source, volume, loop) {
  var audio = new Audio(source)

  audio.volume = volume / 100
  audio.loop = loop

  return audio
}

var myAudio = createAudio('Break & Enter.mp3', 100, true)

myAudio.play()

#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.