HTML5+PHP实现录音功能并上传附源代码下载

来源:程序思维浏览: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 "上传失败";
}
?>

下载源码
精品好课
最新完整React视频教程从入门到精通纯干货纯实战
React是目前最火的前端框架,就业薪资很高,本课程教您如何快速学会React并应用到实战,教你如何解决内存泄漏,常用UI库的使用,自己封装组件,正式上线白屏问题,性能优化等。对正在工作当中或打算学习React高薪就...
jQuery视频教程从入门到精通
jquery视频教程从入门到精通,课程主要包含:jquery选择器、jquery事件、jquery文档操作、动画、Ajax、jquery插件的制作、jquery下拉无限加载插件的制作等等......
HTML5视频播放器video开发教程
适用人群1、有html基础2、有css基础3、有javascript基础课程概述手把手教你如何开发属于自己的HTML5视频播放器,利用mp4转成m3u8格式的视频,并在移动端和PC端进行播放支持m3u8直播格式,兼容...
Vue2+Vue3+ES6+TS+Uni-app开发微信小程序从入门到实战视频教程
2021年最新Vue2+Vue3+ES6+TypeScript和uni-app开发微信小程序从入门到实战视频教程,本课程教你如何快速学会VUE和uni-app并应用到实战,教你如何解决内存泄漏,常用UI库的使用,自己...
HTML5基础入门视频教程易学必会
HTML5基础入门视频教程,教学思路清晰,简单易学必会。适合人群:创业者,只要会打字,对互联网编程感兴趣都可以学。课程概述:该课程主要讲解HTML(学习HTML5的必备基础语言)、CSS3、Javascript(学习...
最新完整React+VUE视频教程从入门到精,企业级实战项目
React和VUE是目前最火的前端框架,就业薪资很高,本课程教您如何快速学会React和VUE并应用到实战,教你如何解决内存泄漏,常用库的使用,自己封装组件,正式上线白屏问题,性能优化等。对正在工作当中或打算学习Re...
React实战视频教程仿京东移动端电商
React是前端最火的框架之一,就业薪资很高,本课程教您如何快速学会React并应用到实战,对正在工作当中或打算学习React高薪就业的你来说,那么这门课程便是你手中的葵花宝典。
VUE2+VUE3视频教程从入门到精通(全网最全的Vue课程)
VUE是目前最火的前端框架之一,就业薪资很高,本课程教您如何快速学会VUE+ES6并应用到实战,教你如何解决内存泄漏,常用UI库的使用,自己封装组件,正式上线白屏问题,性能优化等。对正在工作当中或打算学习VUE高薪就...
收藏
扫一扫关注我们