2016-07-22 153 views
0

我想將兩個音頻合併爲一個,以便與客戶端上的HTML5同步。我已經看到它與Web Audio API可以做很多事情,但我一直無法找到如何。使用HTML5和Javascript同步音頻

我有兩個音頻文件(.mp3,.wav ...)的鏈接,我想要的是同步這兩個音頻文件,如聲音和歌曲。我不想讓他們一個接一個,想要同步。

我會做所有的使用HTML5的客戶端,而不需要使用服務器。這可能嗎?

非常感謝您的幫助。

+0

所以你想要2個音頻文件同時播放? –

+1

嘿米格爾,你可以用https://howlerjs.com,一個基於javascript的音頻庫輕鬆做到這一點 – Phil

+0

嘗試引用此示例,但這與音頻和文本[鏈接](http://happyworm.com/blog/2010/12/05/drumbeat-demo-html5-audio-text-sync /) – Thennarasan

回答

0

所以我明白,你有兩個音頻文件,你想在客戶端上一起渲染。網絡音頻API可以很容易地完全在JavaScript中爲您完成。一個良好的開始是http://www.html5rocks.com/en/tutorials/webaudio/intro/

一個示例腳本是

var context = new(window.AudioContext || window.webkitAudioContext) // Create an audio context 

// Create an XML HTTP Request to collect your audio files 
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest 
var xhr1 = new XMLHttpRequest(); 
var xhr2 = new XMLHttpRequest(); 
var audio_buffer_1, audio_buffer_2; 
xhr1.open("GET","your_url_to_audio_1"); 
xhr1.responseType = 'arraybuffer'; 
xhr1.onload = function() { 
    // Decode the audio data 
    context.decodeAudioData(request.response, function(buffer) { 
    audio_buffer_1 = buffer; 
    }, function(error){}); 
}; 

xhr2.open("GET","your_url_to_audio_2"); 
xhr2.responseType = 'arraybuffer'; 
xhr2.onload = function() { 
    // Decode the audio data 
    context.decodeAudioData(request.response, function(buffer) { 
    audio_buffer_2 = buffer; 
    }, function(error){}); 
}; 

xhr1.send(); 
xhr2.send(); 

這將加載到全局變量audio_buffer_1和audio_buffer_2您的兩個文件的網絡音頻API緩存節點(https://webaudio.github.io/web-audio-api/#AudioBuffer)。

我們創建一個新的音頻緩衝,你需要使用離線音頻上下文

// Assumes both buffers are of the same length. If not you need to modify the 2nd argument below 
var offlineContext = new OfflineAudioContext(context.destination.channelCount,audio_buffer_1.duration*context.sampleRate , context.sampleRate); 
var summing = offlineContext.createGain(); 
summing.connect(offlineContext.destination); 
// Build the two buffer source nodes and attach their buffers 
var buffer_1 = offlineContext.createBufferSource(); 
var buffer_2 = offlineContext.createBufferSource(); 
buffer_1.buffer = audio_buffer_1; 
buffer_2.buffer = audio_buffer_2; 

// Do something with the result by adding a callback 
offlineContext.oncomplete = function(renderedBuffer){ 
    // Place code here 
}; 

//Begin the summing 
buffer_1.start(0); 
buffer_2.start(0); 
offlineContext.startRendering(); 

一旦完成,您將收到名爲renderedBuffer的回調函數內一個新的緩衝,這將是兩人的直接總和緩衝區。