使用h5+即h5plus可以实现调用手机的功能实现语音的录制播放,图片上传下载,拍照,录像的功能,并提供上传下载的功能。开发工具使用hbuilder,该开发工具有模板和demo可以参考实现快速的开发app功能。使用h5调用硬件的功能,实现原生的效果,前端开发app周期短,开发速度快,入门门槛低,hbuilder还提供了一个mui库,可以实现很多手机原生ui的效果。源码下:,
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;" οnclick="startRecord()">开始录音</button>
<!--<button style="width: 150px;height: 80px;color: red;" οnclick="outLine();">开始录音22</button>-->
<button style="width: 150px;height: 80px;color: red;" οnclick="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;" οnchange="uploadImage();">
<!--<input type="button" id="uploadPicButton" value="上传" οnclick="uploadImage()">-->
<br /><br />
<div id="div_image">
</div>
<br />
<hr color="red" />
<br />
<div class="button" οnclick="getImage()">拍照</div>
<br /><br /><br />
<div class="button" οnclick="getVideo()">录像</div>
<br /><br />
<div class="button" id="login">登入</div>
<br />
<div class="button" id="logout">登出</div>
<br />
<div class="button" οnclick="uploadownTest()">下载测试</div>
<!--<label>视频上传:</label><input type="file" name="uploadVideo" accept="video/*" capture="camcorder" id="uploadVideo" style="margin-bottom:10px;" οnchange="uploadVideo();" />-->
<!--<input type="button" id="uploadPicButton" value="上传" οnclick="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" οnclick="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" οnclick="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" οnclick="back()"></div>
<div class="nvtt">wechat</div>
<div class="nvbt idoc" οnclick="openDoc('Camera Document','/doc/camera.html')"></div>
</header>
<div id="dcontent" class="dcontent">
<!--<div class="button" οnclick="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" οnclick="getImage()">拍照</div>
<div class="button" οnclick="getVideo()">录像</div>
<div class="button" οnclick="downloadVideo()">下载</div>
<div class="button" οnclick="uploadAlbumPhoto()">选择相册照片上传</div>
<div class="button" οnclick="getLoginMsg()">获取登入信息</div>
<div class="button" οnclick="websocketTest()">websocket连接</div>
<label>输入信息:</label><input id="msgid" width="300px" height="100px"/>
<div class="button" οnclick="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" οnclick="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,降低学习成本,加速开发。