編輯:現在,它適用於Safari瀏覽器。看起來音頻必須由用戶事件觸發(例如:onclick ..),所以我添加了一個按鈕,並使打字機開始點擊。
PS:缺點是沒有辦法預先加載音頻文件,Safari發出服務器請求並在每次播放音頻時下載音頻。唯一的(骯髒)的方式我能想到的解決方案是提供一個數據URI來代替audioURL ..你可以試試,如果播放速度真的很重要(這會有所幫助:https://www.ibm.com/developerworks/library/wa-ioshtml5/)
// The delay between each keystroke
var delay = 300;
// The typewriter sound file url
var clickURL = "https://cdn.rawgit.com/halimb/res/6ffa798d/typewriter.wav";
// Get a reference to the container div
var container = document.getElementById("container");
var sampleString = "Hello world!";
//get a reference to the start button and typewrite onclick
var start = document.getElementById("btn");
start.onclick = function() { typewrite(sampleString); };
function typewrite(str) {
var i = 0;
container.innerHTML = "";
type();
function type() {
var click = new Audio(clickURL);
// This is triggered when the browser has enough of the file to play through
click.oncanplaythrough = function() {
click.play();
// Add the character to the container div
container.innerHTML += str[i];
i++;
if(i < str.length) {
window.setTimeout(type, delay);
}
}
}
}
* {
\t font-family: Courier;
\t font-size: 32px;
}
.btn {
\t display: inline-block;
\t border: 1px solid black;
\t border-radius: 5px;
\t padding: 10px;
\t cursor: pointer;
\t margin: 10px;
}
<div class="btn" id="btn">Start</div>
<div id="container"></div>
試着想想你想做什麼,打破問題,搜索互聯網上的每個部分,嘗試實施它,然後如果你有問題,請在這裏問問他們! SO並不是提出如此廣泛問題的最佳地點。 – Kroltan