-1

I'm trying to write an if/else statement in Javascript that plays an mp3 audio file when a condition is true. I just want it to start playing without a button like some of the other codes I've seen on here. This is an example of what I have so far.

  var name = function(code) {
    if('Hi.'){
        console.log("Hello.");}
        //This is where I want to add an audio file

    else if('Good morning.'){
        console.log("How are you today?");}
        //This is also where I want to add a file
jc92me
  • 27
  • 1
  • 3
  • 7

2 Answers2

2

This makes some sounds. You must have the sound file in the same folder.

var sound1 = new Audio('file1.mp3'); 
var sound2 = new Audio('file2.mp3');

Then runs your if/else with the audio added added.

var name = function() {
    if('Hi.'){
        console.log("Hello.");
        sound1.play();
    }
    else if('Good morning.'){
        console.log("How are you today?");
        sound2.play();
    }
}

If you want it to just start running then merely add the function name() to the bottom of your code.

name();

This will run the function.

Raven
  • 221
  • 1
  • 4
  • 14
0
function playAudio(filename) {

    var audio = document.createElement("audio");
    audio.preload = "auto";

    var src = document.createElement("source");
    src.src = filename + ".mp3";
    audio.appendChild(src);

    audio.load();
    audio.currentTime = 0.01;
    audio.volume = 1;

    //Due to a bug in Firefox, the audio needs to be played after a delay
    setTimeout(function () {
        soundFile.play();
    }, 1);
}

var name = function (code) {
    if ('Hi.') {
        playAudio("audio.mp3");
    } else if ('Good morning.') {
        console.log("How are you today?");
    }
    playAudio("audio.mp3");
} else {
    //other
}
joe_young
  • 4,107
  • 2
  • 27
  • 38