2015-11-15 44 views
-1

我試圖寫一個if/else語句在JavaScript中播放mp3音頻文件,當條件爲真時。我只想讓它在沒有像我在這裏看到的其他代碼那樣的按鈕的情況下開始播放。 這是我到目前爲止的一個例子。Javascript if/else語句播放MP3音頻文件

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 

回答

0

這使得一些聲音。您必須將聲音文件放在同一個文件夾中。

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

然後運行你的if/else與添加的音頻添加。

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

如果您希望它只是開始運行,那麼只需將函數名稱()添加到代碼的底部即可。

name(); 

這將運行該功能。

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 
}