本篇文章給大家帶來的內容是關於html5實現手機觸摸出現錄音以及離開停止錄音並上傳的功能(代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
以下是實現功能執行個體:
html
<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript" scr="record.js"></script></head><body> <p> <input id="microphone" type="button" /> </p> <script> <script type="text/javascript"> var microDome=document.getElementById('microphone'); var recorder; var btnElem=document.getElementById("microphone");//擷取ID function initEvent() { btnElem.addEventListener("touchstart", function(event) { //event.preventDefault();//阻止瀏覽器預設行為 HZRecorder.get(function (rec) { recorder = rec; recorder.start(); }); }); btnElem.addEventListener("touchend", function(event) { //event.preventDefault(); HZRecorder.get(function (rec) { recorder = rec; recorder.stop(); }) recorder.upload("/upload", function (state, e) { switch (state) { case 'uploading': //var percentComplete = Math.round(e.loaded * 100 / e.total) + '%'; break; case 'ok': //alert(e.target.responseText); alert("上傳成功"); break; case 'error': alert("上傳失敗"); break; case 'cancel': alert("上傳被取消"); break; } }); }); }; initEvent(); <script/>
下面是js:
//相容window.URL = window.URL || window.webkitURL;//擷取電腦的裝置:網路攝影機或者錄音裝置navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;var HZRecorder = function (stream, config) { config = config || {}; config.sampleBits = config.sampleBits || 8; //採樣數位 8, 16 config.sampleRate = config.sampleRate || (44100 / 6); //採樣率(1/6 44100) //建立一個音頻環境對象 var audioContext = window.AudioContext || window.webkitAudioContext; var context = new audioContext(); var audioInput = context.createMediaStreamSource(stream); // 第二個和第三個參數指的是輸入和輸出都是單聲道,2是雙聲道。 var recorder = context.createScriptProcessor(4096, 1, 1); var audioData = { size: 0 //錄音檔案長度 , buffer: [] //錄音緩衝 , inputSampleRate: context.sampleRate //輸入採樣率 , inputSampleBits: 16 //輸入採樣數位 8, 16 , outputSampleRate: config.sampleRate //輸出採樣率 , outputSampleBits: config.sampleBits //輸出採樣數位 8, 16 , input: function (data) { this.buffer.push(new Float32Array(data)); this.size += data.length; } , compress: function () { //合并壓縮 //合并 var data = new Float32Array(this.size); var offset = 0; for (var i = 0; i < this.buffer.length; i++) { data.set(this.buffer[i], offset); offset += this.buffer[i].length; } //壓縮 var compression = parseInt(this.inputSampleRate / this.outputSampleRate); var length = data.length / compression; var result = new Float32Array(length); var index = 0, j = 0; while (index < length) { result[index] = data[j]; j += compression; index++; } return result; } , encodeWAV: function () { var sampleRate = Math.min(this.inputSampleRate, this.outputSampleRate); 、var sampleBits = Math.min(this.inputSampleBits, this.outputSampleBits); var bytes = this.compress(); var dataLength = bytes.length * (sampleBits / 8); var buffer = new ArrayBuffer(44 + dataLength); var data = new DataView(buffer); var channelCount = 1;//單聲道 var offset = 0; var writeString = function (str) { for (var i = 0; i < str.length; i++) { data.setUint8(offset + i, str.charCodeAt(i)); } } // 資源分頁檔標識符 writeString('RIFF'); offset += 4; // 下個地址開始到檔案尾總位元組數,即檔案大小-8 data.setUint32(offset, 36 + dataLength, true); offset += 4; // WAV檔案標誌 writeString('WAVE'); offset += 4; // 波形格式標誌 writeString('fmt '); offset += 4; // 過濾位元組,一般為 0x10 = 16 data.setUint32(offset, 16, true); offset += 4; // 格式類別 (PCM形式採樣資料) data.setUint16(offset, 1, true); offset += 2; // 通道數 data.setUint16(offset, channelCount, true); offset += 2; // 採樣率,每秒樣本數,表示每個通道的播放速度 data.setUint32(offset, sampleRate, true); offset += 4; // 波形資料轉送率 (每秒平均位元組數) 單聲道×每秒資料位元數×每樣本資料位元/8 data.setUint32(offset, channelCount * sampleRate * (sampleBits / 8), true); offset += 4; // 快資料調整數 採樣一次佔用位元組數 單聲道×每樣本的資料位元數/8 data.setUint16(offset, channelCount * (sampleBits / 8), true); offset += 2; // 每樣本資料位元數 data.setUint16(offset, sampleBits, true); offset += 2; // 資料標識符 writeString('data'); offset += 4; // 採樣資料總數,即資料總大小-44 data.setUint32(offset, dataLength, true); offset += 4; // 寫入採樣資料 if (sampleBits === 8) { for (var i = 0; i < bytes.length; i++, offset++) { var s = Math.max(-1, Math.min(1, bytes[i])); var val = s < 0 ? s * 0x8000 : s * 0x7FFF; val = parseInt(255 / (65535 / (val + 32768))); data.setInt8(offset, val, true); } } else { for (var i = 0; i < bytes.length; i++, offset += 2) { var s = Math.max(-1, Math.min(1, bytes[i])); data.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } } return new Blob([data], { type: 'audio/mp3' }); } }; //開始錄音 this.start = function () { audioInput.connect(recorder); recorder.connect(context.destination); } //停止 this.stop = function () { recorder.disconnect(); } //擷取音頻檔案 this.getBlob = function () { this.stop(); return audioData.encodeWAV(); } //上傳 this.upload = function (url, callback) { var fd = new FormData(); fd.append("audioData", this.getBlob()); var xhr = new XMLHttpRequest(); if (callback) { xhr.upload.addEventListener("progress", function (e) { callback('uploading', e); }, false); xhr.addEventListener("load", function (e) { callback('ok', e); }, false); xhr.addEventListener("error", function (e) { callback('error', e); }, false); xhr.addEventListener("abort", function (e) { callback('cancel', e); }, false); } xhr.open("POST", url); xhr.send(fd); } //音頻採集 recorder.onaudioprocess = function (e) { audioData.input(e.inputBuffer.getChannelData(0)); //record(e.inputBuffer.getChannelData(0)); }};//拋出異常// HZRecorder.throwError = function (message) {// alert(message);// throw new function () { this.toString = function () { return message; } }// }//是否支援錄音HZRecorder.canRecording = (navigator.getUserMedia != null);//擷取錄音機HZRecorder.get = function (callback, config) { if (callback) { if (navigator.getUserMedia) { navigator.getUserMedia( { audio: true } //只啟用音頻 , function (stream) { var rec = new HZRecorder(stream, config); callback(rec); } , function (error) { switch (error.code || error.name) { case 'PERMISSION_DENIED': case 'PermissionDeniedError': HZRecorder.throwError('使用者拒絕提供資訊。'); break; case 'NOT_SUPPORTED_ERROR': case 'NotSupportedError': HZRecorder.throwError('瀏覽器不支援硬體裝置。'); break; case 'MANDATORY_UNSATISFIED_ERROR': case 'MandatoryUnsatisfiedError': HZRecorder.throwError('無法發現指定的硬體裝置。'); break; default: HZRecorder.throwError('無法開啟麥克風。異常資訊:' + (error.code || error.name)); break; } }); } else { HZRecorder.throwErr('當前瀏覽器不支援錄音功能。'); return; } }};
這些都是通過大神的講解進行整合後自己摸索出來的,有什麼問題可以評論,我們一起解決,謝謝!!!