h5+實現手機端的錄音,拍照,錄影
阿新 • • 發佈:2019-01-10
使用h5+即h5plus可以實現呼叫手機的功能實現語音的錄製播放,圖片上傳下載,拍照,錄影的功能,並提供上傳下載的功能。開發工具使用hbuilder,該開發工具有模板和demo可以參考實現快速的開發app功能。使用h5呼叫硬體的功能,實現原生的效果,前端開發app週期短,開發速度快,入門門檻低,hbuilder還提供了一個mui庫,可以實現很多手機原生ui的效果。原始碼下:http://download.csdn.net/download/wj903829182/10126959,
1,實現錄音,錄音上傳,錄音下載,錄音播放,主要程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title></title> <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" /> <script src="../js/jquery-3.2.1.min.js"></script> <style type="text/css"> .rp { width: 100%; height: 100%; display: none; text-align: center; position: fixed; top: 0; background: rgba(0, 0, 0, 0.8); z-index: 9999; overflow: hidden; } .aname { font-size: 16px; } .ainf { font-size: 12px; } .rtime { font-size: 22px; color: #FF0000; } .ptime { margin-top: 40%; font-size: 22px; color: #FFFFFF; } .rprogress { background: url(../img/arecord.png) no-repeat center center; background-size: 32px 32px; } .rschedule { background-color: rgba(0, 0, 0, 0); border: 5px solid rgba(0, 183, 229, 0.9); opacity: .9; border-left: 5px solid rgba(0, 0, 0, 0); border-right: 5px solid rgba(0, 0, 0, 0); border-radius: 50px; box-shadow: 0 0 15px #2187e7; width: 36px; height: 36px; margin: 0 auto; -webkit-animation: spin 1s infinite linear; animation: spin 1s infinite linear; } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .progress { width: 90%; background-color: #666; margin: 0 5%; border: 1px solid #222; -webkit-border-radius: 5px; border-radius: 5px; } .schedule { width: 8px; height: 8px; margin: 1px 0; background-color: #FFCC33; -webkit-border-radius: 4px; border-radius: 4px; -webkit-transition: all 1s linear; transition: all 1s linear; } .stop { width: 72px; height: 72px; background: url(../img/astop.png) center center; background-size: 72px 72px; margin: auto; -webkit-border-radius: 72px; border-radius: 72px; } .stop:active { -webkit-box-shadow: 0 3px 8px rgba(0, 0, 0, 0.5) inset; box-shadow: 0 3px 8px rgba(0, 0, 0, 0.5) inset; } .iplay { display: block; background: no-repeat right center url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABYCAYAAAADWlKCAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAKwwAACsMBNCkkqwAAABZ0RVh0Q3JlYXRpb24gVGltZQAwOS8xMi8xM5w+I3MAAAAcdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzVxteM2AAAD9UlEQVR4nO2b3XETMRRGDwzvoYOkg5hRAVkqiKmAdIA7wHSQVECoALsC1gXciV0BTge4gvCwgnHk9d/+WF8m97ztxrlXs8fS1Urym6enJxwd3uZugPMcFyKGCxHDhYjhQsRwIWK4EDFciBguRAwXIoYLEcOFiOFCxHAhYrgQMVyIGC5EDBcihgsRw4WI4ULEcCFiuBAx3uVuwDGY2XtgCBTAALjc8tEFMAdKYBJC+HOK9nXBm5dwUM7MCmAEXDcMMQVuQwhlV23qC2khZjYAboGrjkLOgFEIYd5RvM6RrSFmdgs80J0MYqyHGFsSuR4S60TJ9vrwCEziZ+YhhGXy/xdU9aWgqjfnW+IsgEKtvkgJiUPUPfUyZsD42DoQ68+Y+p62AG6UhjAZITt6xopq3L9vGf+Gqh6dJX+S6ilKNaRkU8YCGLSVARBjDGLMdS5jbgkkhMQiWyejSGtEG2KsghopKoU++5AV68ZDcrvXYWTH8Pghdz1R6CHpN3MFDPsc02PsYcy1qy0nJ6uQOANKZz+jfcOUmd3H6W1jYo5RcvsqtikbuXtI+kBmBxbwz8DczMZtksdcsz1tOinZhMRxPF2bGh8R4gz4amZLMxu2aEqa8zq2LQs5e0j6EB8bLv6dAz/NrGwyjMWcj3vadjJyCimS60nLeFfAbzO7bfANT3MXLdvSmJxCBsl12VHcL8AyvpkfSpo7bdvJyCkkfQfocv5/Bnw3s/mBs6Y097aFzd7JPcv6T5dv5GtcAr/2TZN7yt0IGSE908k0+RS8FiEvhhd1yKEFUw5YAVBApoe0XQrZwgL4GEIY7pLRU+5G5OwhC57PZgbAsqPYK6rdxUMXC9Npbro8fzJy9pB0qll0FPcOuDhCRl3ubEvwOYWUyXXb5YoZ1X7GqMHSfZq7bNmWxuQUki5XnDdc+n4EPoUQiiabSzFnejKl7TJOY7IJid/iaXJ7fESIFfCNas+9zQNMc05zHnjIPctKx/mrA9egflCJGLd5eDFXukGWdddQYU+95PlDWVE97GXPeS+oivf6saBZCKHoM+8+cvcQ2NyhOwMmfW4SxdgTNs9oZd0tBAEhsRDfJbcvgbIPKTtOnNzlPnECAkPWP8xsTv3ZrJ1v2UfmuKDqGRt5QgjZ9kDWyd5D1iioP1U4P3KzqZYYY5v0om38rpDpIeCHrUFMCPjPEeSE/COetf3SU/i7EEL2GVUdSjXkGfGBfWDzIFsb/q93dRizU2R7yDr+o09R/GfRzsmRrSGvFRcihgsRw4WI4ULEcCFiuBAxXIgYLkQMFyKGCxHDhYjhQsRwIWK4EDFciBguRAwXIoYLEcOFiOFCxHAhYrgQMf4CVuqCm+17t3sAAAAASUVORK5CYII=); background-size: 50px 44px; -ms-touch-action: auto; } </style> <!--<script src="../js/voice1.js"></script>--> </head> <body> <div style="height: 200px;widows: 100px;"></div> <div id="dcontent"> <br/> <button style="width: 150px;height: 80px;color: red;" onclick="startRecord()">開始錄音</button> <!--<button style="width: 150px;height: 80px;color: red;" onclick="outLine();">開始錄音22</button>--> <button style="width: 150px;height: 80px;color: red;" onclick="cleanHistory();">清空歷史</button> <br/><br/> <hr color="blanchedalmond" /> <div id="v1"> <!--<audio src="1509952351582.m4a" controls></audio>--> </div> </div> <br /> <hr color="red" /> <label>圖片上傳:</label><input type="file" name="imageName" accept="image/*" id="uploadImage" style="margin-bottom:10px;" onchange="uploadImage();"> <!--<input type="button" id="uploadPicButton" value="上傳" onclick="uploadImage()">--> <br /><br /> <div id="div_image"> </div> <br /> <hr color="red" /> <br /> <div class="button" onclick="getImage()">拍照</div> <br /><br /><br /> <div class="button" onclick="getVideo()">錄影</div> <br /><br /> <div class="button" id="login">登入</div> <br /> <div class="button" id="logout">登出</div> <br /> <div class="button" onclick="uploadownTest()">下載測試</div> <!--<label>視訊上傳:</label><input type="file" name="uploadVideo" accept="video/*" capture="camcorder" id="uploadVideo" style="margin-bottom:10px;" onchange="uploadVideo();" />--> <!--<input type="button" id="uploadPicButton" value="上傳" onclick="uploadImage()">--> <br /><br /> <div id="div_video"> <!--<video src="../audio/1510553447189.mp4" width="400px" height="550px" controls="controls"/>--> <!--<video src="1510553447189.mp4" controls="controls">--> <!--video width="400px" height="550px" controls="controls"> <source src="http://192.168.9.105:8860/v1/uploadDownload/downloadFile?imageName=test.mp4" > 不支援video </video>--> <video src="http://192.168.9.105:8860/v1/uploadDownload/downloadFile?imageName=test2.ogg" controls="controls"> </div> <br /> <div id="play" class="rp"> <div id="ptime" class="ptime">00:00:00/00:00:00</div><br/> <div id="progress" class="progress"> <div id="schedule" class="schedule"></div> </div> <br/> <div class="stop" onclick="stopPlay(),outLine('停止播放!')"></div> </div> <br /> <div id="record" class="rp"> <div style="width:100%;height:20%;"></div> <div class="rprogress"> <div class="rschedule"></div> </div> <br/> <div id="rtime" class="rtime">00:00:00</div><br/> <div class="stop" onclick="stopRecord()"></div> </div> <br /> <div id="output"> Audio用於管理音訊裝置,可呼叫麥克風錄製音訊檔案,也可播放音訊檔案。 </div> </body> <script> var gentry = null, hl = null, le = null; var er = null, ep = null; var bUpdated = false; //用於相容可能提前注入導致DOM未解析完更新的問題 // H5 plus事件處理 function plusReady() { // 獲取音訊目錄物件 plus.io.resolveLocalFileSystemURL('_doc/', function(entry) { entry.getDirectory('audio', { create: true }, function(dir) { gentry = dir; updateHistory(); }, function(e) { outLine('Get directory "audio" failed: ' + e.message); }); }, function(e) { outLine('Resolve "_doc/" failed: ' + e.message); }); } if(window.plus) { plusReady(); } else { document.addEventListener('plusready', plusReady, false); } // DOMContentLoaded事件處理 document.addEventListener('DOMContentLoaded', function() { // 獲取DOM元素物件 hl = document.getElementById('history'); le = document.getElementById('empty'); er = document.getElementById('record'); rt = document.getElementById('rtime'); ep = document.getElementById('play'); pt = document.getElementById('ptime'); pp = document.getElementById('progress') ps = document.getElementById('schedule'); updateHistory(); }, false); // 開始錄音 var r = null, t = 0, ri = null, rt = null; function startRecord() { //outSet('開始錄音:'); console.log('開始錄音:'); r = plus.audio.getRecorder(); if(r == null) { console.log('錄音物件未獲取') outLine('錄音物件未獲取'); return; } r.record({ filename: '_doc/audio/' //format: '3gp' }, function(p) { console.log('錄音完成:' + p) outLine('錄音完成:' + p); plus.io.resolveLocalFileSystemURL(p, function(entry) { //createItem(entry); addVoice(p, entry); }, function(e) { outLine('讀取錄音檔案錯誤:' + e.message); }); }, function(e) { outLine('錄音失敗:' + e.message); }); er.style.display = 'block'; t = 0; ri = setInterval(function() { t++; rt.innerText = timeToStr(t); }, 1000); } // 停止錄音 function stopRecord() { er.style.display = 'none'; rt.innerText = '00:00:00'; clearInterval(ri); ri = null; r.stop(); w = null; r = null; t = 0; } // 清除歷史記錄 function cleanHistory() { //hl.innerHTML = '<li id="empty" class="ditem-empty">無歷史記錄</li>'; //le = document.getElementById('empty'); // 刪除音訊檔案 outLine('清空錄音歷史記錄:'); gentry.removeRecursively(function() { // Success console.log('清空錄音歷史記錄,操作成功!'); outLine('清空錄音歷史記錄,操作成功!'); }, function(e) { console.log('清空錄音歷史記錄,操作失敗:' + e.message); outLine('清空錄音歷史記錄,操作失敗:' + e.message); }); } // 獲取錄音歷史列表 function updateHistory() { if(bUpdated || !gentry || !document.body) { //相容可能提前注入導致DOM未解析完更新的問題 return; } var reader = gentry.createReader(); reader.readEntries(function(entries) { for(var i in entries) { if(entries[i].isFile) { createItem(entries[i]); } } }, function(e) { outLine('讀取錄音列表失敗:' + e.message); }); bUpdated = true; } function outLine(msg) { $('#output').text(msg); } timeToStr = function(ts) { if(isNaN(ts)) { return "--:--:--"; } var h = parseInt(ts / 3600); var m = parseInt((ts % 3600) / 60); var s = parseInt(ts % 60); return(ultZeroize(h) + ":" + ultZeroize(m) + ":" + ultZeroize(s)); }; ultZeroize = function(v, l) { var z = ""; l = l || 2; v = String(v); for(var i = 0; i < l - v.length; i++) { z += "0"; } return z + v; }; function addVoice(path, entry) { console.log("entry = " + entry.name) console.log("上傳前的檔名:" + entry.name); uploadVoice(path); } function uploadVoice(path) { console.log("開始上傳:") var uploadUrl = "http://192.168.9.105:8860/v1/uploadDownload/uploadFile"; var downUrl = "http://192.168.9.105:8860/v1/uploadDownload/downloadFile"; var task = plus.uploader.createUpload(uploadUrl, { method: "POST" }, function(t, status) { //上傳完成 if(status == 200) { var data = JSON.parse(t.responseText); console.log("上傳成功,返回檔名為 :" + data.data); outLine("檔案上傳成功:" + t.responseText); var v = $("<audio controls='controls' volume='1.0'/>"); v.attr("src", downUrl + "?imageName=" + data.data); $("#v1").append(v); //上傳下載成功之後要清除本地的錄音檔案 cleanHistory(); //startPlay(downUrl + "?imageName=" + data.data); /*plus.storage.setItem("uploader", t.responseText); var w = plus.webview.create("uploader_ret.html", "uploader_ret.html", { scrollIndicator: 'none', scalable: false });*/ /*w.addEventListener("loaded", function() { //wt.close(); w.show("slide-in-right", 300); }, false);*/ } else { outLine("上傳失敗:" + status); //wt.close(); } } ); task.addData("client", "HelloH5+"); task.addData("uid", getUid()); /*for(var i = 0; i < files.length; i++) { var f = files[i]; task.addFile(f.path, { key: f.name }); }*/ task.addFile(path, { key: "file" }) task.start(); } // 產生一個隨機數 function getUid() { return Math.floor(Math.random() * 100000000 + 10000000).toString(); } // 播放檔案相關物件 var p = null, pt = null, pp = null, ps = null, pi = null; function startPlay(url) { //ep.style.display = 'block'; //var L = pp.clientWidth; p = plus.audio.createPlayer(url); p.play(function() { outLine('播放完成!'); // 播放完成 /*pt.innerText = timeToStr(d) + '/' + timeToStr(d); ps.style.webkitTransition = 'all 0.3s linear'; ps.style.width = L + 'px'; stopPlay();*/ }, function(e) { outLine('播放音訊檔案"' + url + '"失敗:' + e.message); }); // 獲取總時長 /*var d = p.getDuration(); if(!d) { pt.innerText = '00:00:00/' + timeToStr(d); }*/ /*pi = setInterval(function() { if(!d) { // 相容無法及時獲取總時長的情況 d = p.getDuration(); } var c = p.getPosition(); if(!c) { // 相容無法及時獲取當前播放位置的情況 return; } pt.innerText = timeToStr(c) + '/' + timeToStr(d); var pct = Math.round(L * c / d); if(pct < 8) { pct = 8; } ps.style.width = pct + 'px'; }, 1000);*/ } // 停止播放 function stopPlay() { clearInterval(pi); pi = null; setTimeout(resetPlay, 500); // 操作播放物件 if(p) { p.stop(); p = null; } } // 重置播放頁面內容 function resetPlay() { ep.style.display = 'none'; ps.style.width = '8px'; ps.style.webkitTransition = 'all 1s linear'; pt.innerText = '00:00:00/00:00:00'; } // 拍照 function getImage() { outLine('開始拍照:'); var cmr = plus.camera.getCamera(); cmr.captureImage(function(p) { outLine('拍照成功:' + p); plus.io.resolveLocalFileSystemURL(p, function(entry) { //createItem(entry); uploadPhoto(p, entry); }, function(e) { outLine('讀取拍照檔案錯誤:' + e.message); }); }, function(e) { outLine('失敗:' + e.message); }, { filename: '_doc/camera/', index: 1 }); } // 錄影 function getVideo() { outLine('開始錄影:'); var cmr = plus.camera.getCamera(); console.log("支援錄製的視訊格式:cmr.supportedVideoFormats====="+ cmr.supportedVideoFormats) cmr.startVideoCapture(function(p) { outLine('錄影成功:' + p); plus.io.resolveLocalFileSystemURL(p, function(entry) { //createItem(entry); uploadVideo(p, entry); }, function(e) { outLine('讀取錄影檔案錯誤:' + e.message); }); }, function(e) { outLine('失敗:' + e.message); }, { filename: '_doc/camera/', index: 1 }); } //上傳圖片 function uploadImage() { console.log("開始上傳圖片"); //var file = e.currentTarget.files[0]; var uploadUrl = "http://192.168.9.105:8860/v1/uploadDownload/uploadFile"; var downUrl = "http://192.168.9.105:8860/v1/uploadDownload/downloadFile"; var pic = $('#uploadImage')[0].files[0]; var fd = new FormData(); //fd.append('uploadFile', pic); fd.append('file', pic); $.ajax({ url: uploadUrl, type: "post", // Form資料 data: fd, cache: false, contentType: false, processData: false, success: function(data) { console.log("the data is : {}", data); if(data.code == 0) { console.log("上傳成功後的檔案路徑為:" + data.data); var img = $("<img />"); img.attr("src", downUrl + "?imageName=" + data.data); img.width("160px"); img.height("160px"); $("#div_image").append(img); } } }); } //上傳拍照 function uploadPhoto(path, entry) { console.log("開始上傳拍照:"); var uploadUrl = "http://192.168.9.105:8860/v1/uploadDownload/uploadFile"; var downUrl = "http://192.168.9.105:8860/v1/uploadDownload/downloadFile"; var task = plus.uploader.createUpload(uploadUrl, { method: "POST" }, function(t, status) { //上傳完成 if(status == 200) { var data = JSON.parse(t.responseText); console.log("上傳成功,返回檔名為 :" + data.data); outLine("檔案上傳成功:" + t.responseText); //上傳下載成功之後要清除本地的圖片檔案 var img = $("<img />"); img.attr("src", downUrl + "?imageName=" + data.data); img.width("160px"); img.height("160px"); $("#div_image").append(img); cleanHistory(); } else { outLine("上傳失敗:" + status); //wt.close(); } } ); task.addData("client", "HelloH5+"); task.addData("uid", getUid()); task.addFile(path, { key: "file" }) task.start(); } //上傳錄影 function uploadVideo(path, entry) { console.log("開始上傳錄影:path="+path); var uploadUrl = "http://192.168.9.105:8860/v1/uploadDownload/uploadFile"; var downUrl = "http://192.168.9.105:8860/v1/uploadDownload/downloadFile"; var task = plus.uploader.createUpload(uploadUrl, { method: "POST" }, function(t, status) { //上傳完成 if(status == 200) { var data = JSON.parse(t.responseText); console.log("上傳成功,返回檔名為 :" + data.data); outLine("檔案上傳成功:" + t.responseText); //上傳下載成功之後要清除本地的圖片檔案 var v = $("<video width='320' width='240' preload='auto' controls='controls'/>"); v.attr("src", downUrl + "?imageName=" + data.data); //v.attr("src", path); //v.attr("id", data.data); $("#div_video").append(v); //cleanHistory(); } else { outLine("上傳失敗:" + status); //wt.close(); } } ); task.addData("client", "HelloH5+"); task.addData("uid", getUid()); task.addFile(path, { key: "file" }) task.start(); } function test1() { alert(537); } function uploadownTest(){ } // 使用者名稱登入 $('#login').click(function(){ console.log(4444444); //$("#f2").submit(); var param ={'username':'jack','password':'jack'}; $.ajax({ type: 'POST', url: 'http://xx.xx.xx.xx:xx/login', //url: publicUrl+'/login', data: param, xhrFields: { withCredentials: true }, crossDomain: true, success: function(data){ console.log(data); if(data.data && data.data.success && data.data.userDetails.username){ //window.location.href = "./index.html"; outLine(data); } } }) }); // 使用者名稱登出 $('#logout').click(function(){ $.ajax({ type: 'POST', url: publicUrl+'/logout', xhrFields: { withCredentials: true }, crossDomain: true, success: function(data){ if((data.data && data.data) || data.code == 100){ //window.location.href = "login.html"; outLine(data); } } }) }); </script> </html>
2,實現拍照,錄影,上傳下載,播放,websocket連線
主要程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="HandheldFriendly" content="true" /> <meta name="MobileOptimized" content="320" /> <title>wechat</title> <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" /> </head> <body> <header id="header"> <div class="nvbt iback" onclick="back()"></div> <div class="nvtt">wechat</div> <div class="nvbt idoc" onclick="openDoc('Camera Document','/doc/camera.html')"></div> </header> <div id="dcontent" class="dcontent"> <!--<div class="button" onclick="changeIndex();"> 選擇:<span id="display" style="color:#FF0000">主攝像頭</span> <div style="width:0px;height:0px;overflow:hidden;"><select id="index"> <option value='1' selected="true">主攝像頭</option> <option value='2' >輔攝像頭</option> </select></div> </div>--> <div class="button" onclick="getImage()">拍照</div> <div class="button" onclick="getVideo()">錄影</div> <div class="button" onclick="downloadVideo()">下載</div> <div class="button" onclick="uploadAlbumPhoto()">選擇相簿照片上傳</div> <div class="button" onclick="getLoginMsg()">獲取登入資訊</div> <div class="button" onclick="websocketTest()">websocket連線</div> <label>輸入資訊:</label><input id="msgid" width="300px" height="100px"/> <div class="button" onclick="sendMsg()">傳送訊息</div> <br/><br /> <div id="div_video"> </div> <div id="websocket_div"></div> <!-- History list --> <ul id="history" class="dlist" style="text-align:left;"> <li id="empty" class="ditem-empty">無歷史記錄</li> </ul> <br/> <div class="button button-waring" onclick="cleanHistory()">清空歷史記錄</div> <br/> </div> <br /> <div id="output"> Camera管理攝像頭裝置,可用於拍攝照片、錄製視訊檔案。 </div> </body> <!--樣式:--> <!--js--> <script type="text/javascript" src="../js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="../js/immersed.js"></script> <script type="text/javascript" src="../js/sockjs.min.js"></script> <!--<script type="text/javascript" src="../js/common.js"></script>--> <script> var i = 1, gentry = null, w = null; var hl = null, le = null, de = null, ie = null; var unv = true; var bUpdated = false; //用於相容可能提前注入導致DOM未解析完更新的問題 var downloads = null; // H5 plus事件處理 function plusReady() { // 獲取攝像頭目錄物件 plus.io.resolveLocalFileSystemURL('_doc/', function(entry) { entry.getDirectory('camera', { create: true }, function(dir) { gentry = dir; console.log("gentry=" + gentry); //updateHistory(); }, function(e) { outSet('Get directory "camera" failed: ' + e.message); }); }, function(e) { outSet('Resolve "_doc/" failed: ' + e.message); }); } if(window.plus) { plusReady(); } else { document.addEventListener('plusready', plusReady, false); } // 監聽DOMContentLoaded事件 document.addEventListener('DOMContentLoaded', function() { // 獲取DOM元素物件 hl = document.getElementById('history'); le = document.getElementById('empty'); de = document.getElementById('display'); if(ie = document.getElementById('index')) { ie.onchange = indexChanged; } // 判斷是否支援video標籤 unv = !document.createElement('video').canPlayType; //updateHistory(); }, false); var ws = plus.webview.currentWebview(); function back(hide) { if(plus) { ws || (ws = plus.webview.currentWebview()); if(hide || ws.preate) { ws.hide('auto'); } else { ws.close('auto'); } } else if(history.length > 1) { history.back(); } else { window.close(); } }; // 錄影 function getVideo() { outSet('開始錄影:'); var cmr = plus.camera.getCamera(); cmr.startVideoCapture(function(p) { outLine('成功:' + p); console.log("錄製視訊成功,路徑為:" + p); plus.io.resolveLocalFileSystemURL(p, function(entry) { //createItem(entry); playVideo(p, entry); }, function(e) { outLine('讀取錄影檔案錯誤:' + e.message); }); }, function(e) { outLine('失敗:' + e.message); }, { filename: '_doc/camera/', index: i }); } //播放視訊 function playVideo(path, entry) { console.log("entry.name=" + entry.name); console.log("entry.toLocalURL()=" + entry.toLocalURL()); console.log("gentry.toLocalURL()=" + gentry.toLocalURL()); var localUrl = encodeURI("http://192.168.9.105:8860/v1/uploadDownload/downloadFile?imageName=1510553721741.mp4"); console.log(localUrl); //var localUrl = entry.toLocalURL(); var v = $("<video width='400' height='320' preload='auto' controls='controls' type='video/mp4'/>"); v.attr("src", localUrl); $("#div_video").append(v); /*if(w) { outLine('重複點選!'); return; } if(!entry) { ouSet('無效的媒體檔案'); return; } var name = entry.name; var suffix = name.substr(name.lastIndexOf('.')); var url = ''; if(suffix == '.mov' || suffix == '.3gp' || suffix == '.mp4' || suffix == '.avi') { //if(unv){plus.runtime.openFile('_doc/camera/'+name);return;} url = '/plus/camera_video.html'; } else { url = '/plus/camera_image.html'; } w = plus.webview.create(url, url, { hardwareAccelerated: true, scrollIndicator: 'none', scalable: true, bounce: 'all' }); w.addEventListener('loaded', function() { w.evalJS('loadMedia("' + entry.toLocalURL() + '")'); //w.evalJS('loadMedia("'+'http://localhost:13131/_doc/camera/'+name+'")'); }, false); w.addEventListener('close', function() { w = null; }, false); w.show('pop-in');*/ } function outSet(msg) { $('#output').text(msg); } function outLine(msg) { $('#output').text(msg); } function downloadVideo() { console.log("進行下載......"); var downloadUrl = "http://192.168.9.105:8860/v1/uploadDownload/downloadFile?imageName=1510556514121.mp4"; var dtask = plus.downloader.createDownload(downloadUrl, { filename: '_doc/camera/', priority: 90 }, function(d, status) { // 下載完成 if(status == 200) { console.log("下載視訊成功....."); //視訊下載到本地後的真實路徑 var sd_path = plus.io.convertLocalFileSystemURL(d.filename); console.log("sd_path=" + sd_path); console.log("filename is : " + d.filename); var v = $("<video width='400' height='320' preload='auto' controls='controls' type='video/mp4'/>"); v.attr("src", sd_path); $("#div_video").append(v); } else { console.log("下載視訊失敗....." + status) } }); //dtask.addEventListener( "statechanged", onStateChanged, false ); dtask.start(); } function uploadAlbumPhoto() { } //websocket 操作: var websocket; function websocketTest() { var websocketUrl = "ws://192.168.9.105:8860/webSocketServer?topic=jack1,jack2,chat"; if('WebSocket' in window) { console.log("222"); websocket = new WebSocket(websocketUrl); console.log("3333"); } else if('MozWebSocket' in window) { websocket = new MozWebSocket("ws://" + document.location.host + "/webSocketServer"); } else { websocket = new SockJS("http://" + document.location.host + "/sockjs/webSocketServer"); } websocket.onopen = function(event) { console.log("onopen----", event.data); }; websocket.onmessage = function(event) { //var e= event|| window.event; //$("#test").html(evnt.data); //console.log(event); //var data = event.data; console.log("onmessage----", event.data); $("#websocket_div").append('<div>' + event.data + '</div>'); }; websocket.onerror = function(event) { console.log("onerror----", event.data); } websocket.onclose = function(event) { console.log("onclose----", event.data); } } function sendMsg() { if(websocket.readyState == websocket.OPEN) { var msg = $('#msgid').val(); //呼叫後臺handleTextMessage方法 var json = { "msg": msg, "type": "chat" }; //websocket.send(msg); websocket.send(JSON.stringify(json)); } else { alert("連線失敗!"); } } function getLoginMsg() { var publicUrl = "http://192.168.9.105:8865"; $.ajax({ type: 'GET', url: publicUrl + '/station-user/v1/session/sessionInfo', xhrFields: { withCredentials: true }, crossDomain: true, success: function(data) { console.log(data); $("#websocket_div").append('<div>' + JSON.stringify(data) + '</div>'); } }) } </script> </html>
程式碼有點亂,主要是實現功能,使用h5plus的功能,呼叫手機的功能,實現原生app的效果,使用hbuilder打包apk到手機上執行,檢視效果。
利用前端技術,快速開發原生app,降低學習成本,加速開發。