2017-09-23 20 views
0

我需要模擬一箇舊的手動打字機在打印網頁上輸入內容時的功能。我想開發JavaScript函數來傳遞一個字符串,並且它會延遲打印每個字符,並且聲音文件與每個字母同步。如何同步打印帶有聲音的字符?

我是JavaScript新手。什麼是這樣做的首選方法?我應該看看jQuery嗎?或者這很簡單嗎?

我見過在某些網絡瀏覽器上這樣觸發聲音文件的問題,有沒有最適合這種事情的音頻文件格式?

我發現這一點,但問題是,它不是在所有的Web瀏覽器上: https://rawgit.com/mehaase/js-typewriter/master/example3-typewriter/index.html

+0

試着想想你想做什麼,打破問題,搜索互聯網上的每個部分,嘗試實施它,然後如果你有問題,請在這裏問問他們! SO並不是提出如此廣泛問題的最佳地點。 – Kroltan

回答

1

編輯:現在,它適用於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>

+0

不錯!你有什麼想法,爲什麼這可以在Google Chrome/Mac上運行,但它不適用於Safari/Mac?沒有聲音。 –

+1

它現在在safari上工作 – Halim

+0

我在其他地方讀過一個建議,使用ogg代替wav文件用於Safari可能會更好嗎?你有什麼想法嗎? –