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日

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM