html 录音并上传

本篇呢是本人前几天做录音上传的时候借鉴的一些方法

整合一下,主要借鉴了以下三位大大的博客


基础版本

借鉴于博客:

 : https://blog.csdn.net/weixin_44797182/article/details/107684685


然后进阶版本的:

借鉴于博客:

星际毁灭  : https://www.cnblogs.com/wys-373/p/12431673.html


最后最终极版本的

也是初级版本和进阶版本大大借鉴的博客

借鉴于博客:

xiangyuecn  :  https://www.cnblogs.com/xiangyuecn/p/11410312.html

大大的Github:https://github.com/xiangyuecn/Recorder

觉得帮助到的可以去支持下哈


本人用的最初版本

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head> 
<body>
    <!-- 先加载js录音库,注意:你应该把js clone到本地使用 --><meta charset="utf-8" />
<script src="https://xiangyuecn.github.io/Recorder/recorder.mp3.min.js"></script>

<input type="button" onclick="startRec()" value="开始录音">
<hr>
<input type="button" onclick="playRec()" value="结束并播放">
<input type="button" onclick="uploadRec()" value="结束并上传">

<script> 
var rec;
function startRec(){
    rec=Recorder();//使用默认配置,mp3格式
    //打开麦克风授权获得相关资源
    rec.open(function(){
        //开始录音
        rec.start();
    },function(msg,isUserNotAllow){
        //用户拒绝了权限或浏览器不支持
        alert((isUserNotAllow?"用户拒绝了权限,":"")+"无法录音:"+msg);
    });
};
</script>
<script>
    function uploadRec(){
        //停止录音,得到了录音文件blob二进制对象,想干嘛就干嘛
        rec.stop(function(blob,duration){
            /*
            blob文件对象,可以用FileReader读取出内容
            ,或者用FormData上传,本例直接上传二进制文件
            ,对于普通application/x-www-form-urlencoded表单上传
            ,请参考github里面的例子
            */
            var form=new FormData();
            form.append("upfile",blob,"recorder.mp3"); //和普通form表单并无二致,后端接收到upfile参数的文件,文件名为recorder.mp3
            
            //直接用ajax上传
            var xhr=new XMLHttpRequest();
            xhr.open("POST","http://baidu.com/修改成你的上传地址");//这个假地址在控制台network中能看到请求数据和格式,请求结果无关紧要
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    alert(xhr.status==200?"上传成功":"测试请先打开浏览器控制台,然后重新录音,在network选项卡里面就能看到上传请求数据和格式了");
                }
            }
            xhr.send(form);
        },function(msg){
            alert("录音失败:"+msg);
        });
    };</script>
    <script>
        function playRec(){
            //停止录音,得到了录音文件blob二进制对象,想干嘛就干嘛
            rec.stop(function(blob,duration){
                var audio=document.createElement("audio");
                audio.controls=true;
                document.body.appendChild(audio);
                
                //非常简单的就能拿到blob音频url
                audio.src=URL.createObjectURL(blob);
                audio.play();
            },function(msg){
                alert("录音失败:"+msg);
            });
        };</script>
</body>
</html>

以上即是全部内容

2020年08月28日

原文地址:https://www.cnblogs.com/YFYQ/p/13575594.html