HTML5+PHP实现录音功能并上传附源代码下载
日期:2018-03-16
来源:程序思维浏览:4544次
这几天在做一个WEB端口试系统,需要利用HTML5和PHP实现录音功能并上传到服务器,下面我将代码公开让大家来学习,希望对大家有帮助。
1、index.html页面代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Html5网页JavaScript录制MP3音频</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Html5网页JavaScript录制MP3音频</h1>
<button onclick="funStart(this);" id="btnStart" disabled>录制</button>
<button onclick="funStop(this);" id="btnStop" disabled>停止</button>
<button onclick="funUpload(this);" id="btnUpload" disabled>上传</button>
<h4>调试信息:</h4>
<div id="recordingslist"></div>
<script src="js/recordmp3.js"></script>
<script>
var recorder = new MP3Recorder({
debug:true,
funOk: function () {
btnStart.disabled = false;
log('初始化成功');
},
funCancel: function (msg) {
log(msg);
recorder = null;
}
});
var mp3Blob;
function funStart(button) {
btnStart.disabled = true;
btnStop.disabled = false;
btnUpload.disabled = true;
log('录音开始...');
recorder.start();
}
function funStop(button) {
recorder.stop();
btnStart.disabled = false;
btnStop.disabled = true;
btnUpload.disabled = false;
log('录音结束,MP3导出中...');
recorder.getMp3Blob(function (blob) {
log('MP3导出成功');
mp3Blob = blob;
var url = URL.createObjectURL(mp3Blob);
var div = document.createElement('div');
var au = document.createElement('audio');
var hf = document.createElement('a');
au.controls = true;
au.src = url;
hf.href = url;
hf.download = new Date().toISOString() + '.mp3';
hf.innerHTML = hf.download;
div.appendChild(au);
div.appendChild(hf);
recordingslist.appendChild(div);
});
}
function log(str) {
recordingslist.innerHTML += str + '<br/>';
}
function funUpload() {
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
fd.append('mp3Name', mp3Name);
fd.append('file', mp3Blob);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
recordingslist.innerHTML += '上传成功:<a href="' + xhr.responseText + '" target="_blank">' + mp3Name + '</a>';
}
};
xhr.open('POST', 'upload.php');
xhr.send(fd);
}
</script>
</body>
</html>
2、recordmp3.js转mp3插件代码:
(function (exports) {
var MP3Recorder = function (config) {
var recorder = this;
config = config || {};
config.sampleRate = config.sampleRate || 44100;
config.bitRate = config.bitRate || 128;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
},
function (stream) {
var context = new AudioContext(),
microphone = context.createMediaStreamSource(stream),
processor = context.createScriptProcessor(16384, 1, 1),//bufferSize大小,输入channel数,输出channel数
mp3ReceiveSuccess, currentErrorCallback;
config.sampleRate = context.sampleRate;
processor.onaudioprocess = function (event) {
//边录音边转换
var array = event.inputBuffer.getChannelData(0);
realTimeWorker.postMessage({ cmd: 'encode', buf: array });
};
var realTimeWorker = new Worker('js/worker-realtime.js');
realTimeWorker.onmessage = function (e) {
switch (e.data.cmd) {
case 'init':
log('初始化成功');
if (config.funOk) {
config.funOk();
}
break;
case 'end':
log('MP3大小:', e.data.buf.length);
if (mp3ReceiveSuccess) {
mp3ReceiveSuccess(new Blob(e.data.buf, { type: 'audio/mp3' }));
}
break;
case 'error':
log('错误信息:' + e.data.error);
if (currentErrorCallback) {
currentErrorCallback(e.data.error);
}
break;
default:
log('未知信息:', e.data);
}
};
recorder.getMp3Blob = function (onSuccess, onError) {
currentErrorCallback = onError;
mp3ReceiveSuccess = onSuccess;
realTimeWorker.postMessage({ cmd: 'finish' });
};
recorder.start = function () {
if (processor && microphone) {
microphone.connect(processor);
processor.connect(context.destination);
log('开始录音');
}
}
recorder.stop = function () {
if (processor && microphone) {
microphone.disconnect();
processor.disconnect();
log('录音结束');
}
}
realTimeWorker.postMessage({
cmd: 'init',
config: {
sampleRate: config.sampleRate,
bitRate: config.bitRate
}
});
},
function (error) {
var msg;
switch (error.code || error.name) {
case 'PERMISSION_DENIED':
case 'PermissionDeniedError':
msg = '用户拒绝访问麦客风';
break;
case 'NOT_SUPPORTED_ERROR':
case 'NotSupportedError':
msg = '浏览器不支持麦客风';
break;
case 'MANDATORY_UNSATISFIED_ERROR':
case 'MandatoryUnsatisfiedError':
msg = '找不到麦客风设备';
break;
default:
msg = '无法打开麦克风,异常信息:' + (error.code || error.name);
break;
}
if (config.funCancel) {
config.funCancel(msg);
}
});
} else {
if (config.funCancel) {
config.funCancel('当前浏览器不支持录音功能');
}
}
function log(str) {
if (config.debug) {
console.log(str);
}
}
}
exports.MP3Recorder = MP3Recorder;
})(window);
3、upload.php上传文件代码:
<?php
$file=$_FILES["file"]["tmp_name"];
if(move_uploaded_file($file,"upload/".time().".mp3")){
echo "上传成功!";
}else{
echo "上传失败";
}
?>
下载源码
1、index.html页面代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Html5网页JavaScript录制MP3音频</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Html5网页JavaScript录制MP3音频</h1>
<button onclick="funStart(this);" id="btnStart" disabled>录制</button>
<button onclick="funStop(this);" id="btnStop" disabled>停止</button>
<button onclick="funUpload(this);" id="btnUpload" disabled>上传</button>
<h4>调试信息:</h4>
<div id="recordingslist"></div>
<script src="js/recordmp3.js"></script>
<script>
var recorder = new MP3Recorder({
debug:true,
funOk: function () {
btnStart.disabled = false;
log('初始化成功');
},
funCancel: function (msg) {
log(msg);
recorder = null;
}
});
var mp3Blob;
function funStart(button) {
btnStart.disabled = true;
btnStop.disabled = false;
btnUpload.disabled = true;
log('录音开始...');
recorder.start();
}
function funStop(button) {
recorder.stop();
btnStart.disabled = false;
btnStop.disabled = true;
btnUpload.disabled = false;
log('录音结束,MP3导出中...');
recorder.getMp3Blob(function (blob) {
log('MP3导出成功');
mp3Blob = blob;
var url = URL.createObjectURL(mp3Blob);
var div = document.createElement('div');
var au = document.createElement('audio');
var hf = document.createElement('a');
au.controls = true;
au.src = url;
hf.href = url;
hf.download = new Date().toISOString() + '.mp3';
hf.innerHTML = hf.download;
div.appendChild(au);
div.appendChild(hf);
recordingslist.appendChild(div);
});
}
function log(str) {
recordingslist.innerHTML += str + '<br/>';
}
function funUpload() {
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
fd.append('mp3Name', mp3Name);
fd.append('file', mp3Blob);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
recordingslist.innerHTML += '上传成功:<a href="' + xhr.responseText + '" target="_blank">' + mp3Name + '</a>';
}
};
xhr.open('POST', 'upload.php');
xhr.send(fd);
}
</script>
</body>
</html>
2、recordmp3.js转mp3插件代码:
(function (exports) {
var MP3Recorder = function (config) {
var recorder = this;
config = config || {};
config.sampleRate = config.sampleRate || 44100;
config.bitRate = config.bitRate || 128;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
},
function (stream) {
var context = new AudioContext(),
microphone = context.createMediaStreamSource(stream),
processor = context.createScriptProcessor(16384, 1, 1),//bufferSize大小,输入channel数,输出channel数
mp3ReceiveSuccess, currentErrorCallback;
config.sampleRate = context.sampleRate;
processor.onaudioprocess = function (event) {
//边录音边转换
var array = event.inputBuffer.getChannelData(0);
realTimeWorker.postMessage({ cmd: 'encode', buf: array });
};
var realTimeWorker = new Worker('js/worker-realtime.js');
realTimeWorker.onmessage = function (e) {
switch (e.data.cmd) {
case 'init':
log('初始化成功');
if (config.funOk) {
config.funOk();
}
break;
case 'end':
log('MP3大小:', e.data.buf.length);
if (mp3ReceiveSuccess) {
mp3ReceiveSuccess(new Blob(e.data.buf, { type: 'audio/mp3' }));
}
break;
case 'error':
log('错误信息:' + e.data.error);
if (currentErrorCallback) {
currentErrorCallback(e.data.error);
}
break;
default:
log('未知信息:', e.data);
}
};
recorder.getMp3Blob = function (onSuccess, onError) {
currentErrorCallback = onError;
mp3ReceiveSuccess = onSuccess;
realTimeWorker.postMessage({ cmd: 'finish' });
};
recorder.start = function () {
if (processor && microphone) {
microphone.connect(processor);
processor.connect(context.destination);
log('开始录音');
}
}
recorder.stop = function () {
if (processor && microphone) {
microphone.disconnect();
processor.disconnect();
log('录音结束');
}
}
realTimeWorker.postMessage({
cmd: 'init',
config: {
sampleRate: config.sampleRate,
bitRate: config.bitRate
}
});
},
function (error) {
var msg;
switch (error.code || error.name) {
case 'PERMISSION_DENIED':
case 'PermissionDeniedError':
msg = '用户拒绝访问麦客风';
break;
case 'NOT_SUPPORTED_ERROR':
case 'NotSupportedError':
msg = '浏览器不支持麦客风';
break;
case 'MANDATORY_UNSATISFIED_ERROR':
case 'MandatoryUnsatisfiedError':
msg = '找不到麦客风设备';
break;
default:
msg = '无法打开麦克风,异常信息:' + (error.code || error.name);
break;
}
if (config.funCancel) {
config.funCancel(msg);
}
});
} else {
if (config.funCancel) {
config.funCancel('当前浏览器不支持录音功能');
}
}
function log(str) {
if (config.debug) {
console.log(str);
}
}
}
exports.MP3Recorder = MP3Recorder;
})(window);
3、upload.php上传文件代码:
<?php
$file=$_FILES["file"]["tmp_name"];
if(move_uploaded_file($file,"upload/".time().".mp3")){
echo "上传成功!";
}else{
echo "上传失败";
}
?>
下载源码
精品好课