1. 程式人生 > >超實用的HTML 5介面全方位測試總結文(一)

超實用的HTML 5介面全方位測試總結文(一)

目錄:

一、讓音樂隨心而動 – 音訊處理 Web audio API
二、捕捉使用者攝像頭 – 媒體流 Media Capture
三、你是逗逼? – 語音識別 Web Speech API
四、讓我盡情呵護你 – 裝置電量 Battery API
五、獲取使用者位置 – 地理位置 Geolocation API
六、把使用者捧在手心 – 環境光 Ambient Light API
七、陀螺儀 Deviceorientation
八、Websocket
九、NFC
十、震動 – Vibration API
十一、網路環境 Connection API

一、讓音樂隨心而動 – 音訊處理 Web audio API

簡介:

Audio物件提供的只是音訊檔案的播放,而Web Audio則是給了開發者對音訊資料進行分析、處理的能力,比如混音、過濾。

系統要求:

ios6+、android chrome、android firefox

例項:

核心程式碼:

var context = new webkitAudioContext();
var source = context.createBufferSource();   // 建立一個聲音源
source.buffer = buffer;   // 告訴該源播放何物 
createBufferSourcesource.connect(context.destination);   // 將該源與硬體相連
source.start(0); //播放
技術分析:

當我們載入完音訊資料後,我們將建立一個全域性的AudioContext物件來對音訊進行處理,AudioContext可以建立各種不同功能型別的音訊節點AudioNode,比如

1、源節點(source node)

我們可以使用兩種方式載入音訊資料:

<1>、audio標籤

var sound, audio = new Audio();
audio.addEventListener('canplay', function() {
 sound = context.createMediaElementSource(audio);
 sound.connect(context.destination);
});
audio.src = '/audio.mp3';

<2>、XMLHttpRequest

var sound, context = createAudioContext();
var audioURl = '/audio.mp3'; // 音訊檔案URL
var xhr = new XMLHttpRequest();
xhr.open('GET', audioURL, true);
xhr.responseType = 'arraybuffer'; 
xhr.onload = function() {
 context.decodeAudioData(request.response, function (buffer) {
 source = context.createBufferSource();
 source.buffer = buffer;
 source.connect(context.destination);
 }
}
xhr.send();

2、分析節點(analyser node)

我們可以使用AnalyserNode來對音譜進行分析,例如:

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);

function draw() {
 drawVisual = requestAnimationFrame(draw);
 analyser.getByteTimeDomainData(dataArray);
 // 將dataArray資料以canvas方式渲染出來
};

draw();

3、處理節點(gain node、panner node、wave shaper node、delay node、convolver node等)

不同的處理節點有不同的作用,比如使用BiquadFilterNode調整音色(大量濾波器)、使用ChannelSplitterNode分割左右聲道、使用GainNode調整增益值實現音樂淡入淡出等等。

4、目的節點(destination node)

所有被渲染音訊流到達的最終地點

思維發散:

1、可以讓CSS3動畫跟隨背景音樂舞動,可以為我們的網頁增色不少;
2、可以嘗試製作H5酷酷的變聲應用,增加與使用者的互動;
3、甚至可以嘗試H5音樂創作。

二、捕捉使用者攝像頭 – 媒體流 Media Capture

簡介:

通過getUserMedia捕捉使用者攝像頭獲取視訊流和通過麥克風獲取使用者聲音。

系統要求:

android chrome、android firefox

例項:

捕獲使用者攝像頭 捕獲使用者麥克風

核心程式碼:

1、攝像頭捕捉

navigator.webkitGetUserMedia ({video: true}, function(stream) {
 video.src = window.URL.createObjectURL(stream);
 localMediaStream = stream;
}, function(e){

})

2、從視訊流中拍照

btnCapture.addEventListener('touchend', function(){
	if (localMediaStream) {
		canvas.setAttribute('width', video.videoWidth);
		canvas.setAttribute('height', video.videoHeight);
		ctx.drawImage(video, 0, 0);
	}
}, false);

3、使用者聲音錄製

navigator.getUserMedia({audio:true}, function(e) {
	context = new audioContext();
	audioInput = context.createMediaStreamSource(e);	
	volume = context.createGain();
	recorder = context.createScriptProcessor(2048, 2, 2);
	recorder.onaudioprocess = function(e){
		recordingLength += 2048;
		recorder.connect (context.destination); 
	}	
}, function(error){});

4、儲存使用者錄製的聲音

var buffer = new ArrayBuffer(44 + interleaved.length * 2);
var view = new DataView(buffer);
fileReader.readAsDataURL(blob); // android chrome audio不支援blob
… audio.src = event.target.result;

思維發散:

1、從視訊拍照自定義頭像;
2、H5視訊聊天;
3、結合canvas完成好玩的照片合成及處理;
4、結合Web Audio製作有意思變聲應用。

三、你是逗逼? – 語音識別 Web Speech API簡介:

1、將文字轉換成語音;
2、將語音識別為文字。

系統要求:
ios7+,android chrome,android firefox

測試例項:

核心程式碼:

1、文字轉換成語音,使用SpeechSynthesisUtterance物件;

var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.volume = 1; // 0 to 1
msg.text = ‘識別的文字內容’;
msg.lang = 'en-US';
speechSynthesis.speak(msg);

2、語音轉換為文字,使用SpeechRecognition物件。

var newRecognition = new webkitSpeechRecognition();
newRecognition.onresult = function(event){
	var interim_transcript = ''; 
	for (var i = event.resultIndex; i < event.results.length; ++i) {
		final_transcript += event.results[i][0].transcript;
	}
};

測試結論:

1、Android支援不穩定;語音識別測試失敗(暫且認為是某些內建介面被牆所致)。

思維發散:

1、當語音識別成為可能,那聲音控制將可以展示其強大的功能。在某些場景,比如開車、網路電視,聲音控制將大大改善使用者體驗;
2、H5遊戲中最終分數播報,股票資訊實時聲音提示,Web Speech都可以大放異彩。

 四、讓我盡情呵護你 – 裝置電量 Battery API簡介:

查詢使用者裝置電量及是否正在充電。

系統要求:

android firefox

測試例項:

核心程式碼:

var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery;
var str = '';
if (battery) {
 str += '<p>你的瀏覽器支援HTML5 Battery API</p>';
 if(battery.charging) {
 str += '<p>你的裝置正在充電</p>';
} else {
 str += '<p>你的裝置未處於充電狀態</p>';
}
 str += '<p>你的裝置剩餘'+ parseInt(battery.level*100)+'%的電量</p>';
} else {
 str += '<p>你的瀏覽器不支援HTML5 Battery API</p>';
}

測試結論:

1、QQ瀏覽器與UC瀏覽器支援該介面,但未正確顯示裝置電池資訊;
2、caniuse顯示android chrome42支援該介面,實測不支援。

思維發散:

相對而言,我覺得這個介面有些雞肋。
很顯然,並不合適用HTML5做電池管理方面的工作,它所提供的許可權也很有限。
我們只能嘗試做一些優化使用者體驗的工作,當用戶裝置電量不足時,進入省電模式,比如停用濾鏡、攝像頭開啟、webGL、減少網路請求等。

 五、獲取使用者位置 – 地理位置 Geolocation簡介:

Geolocation API用於將使用者當前地理位置資訊共享給信任的站點,目前主流移動裝置都能夠支援。

系統要求:

ios6+、android2.3+

測試例項:

核心程式碼:

var domInfo = $("#info");

// 獲取位置座標
if (navigator.geolocation) {
	navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
	domInfo.innerHTML="抱歉,你的瀏覽器不支援地理定位!";
}

// 使用騰訊地圖顯示位置
function showPosition(position) {
	var lat=position.coords.latitude;
	var lon=position.coords.longitude;

	mapholder = $('#mapholder')
	mapholder.style.height='250px';
	mapholder.style.width = document.documentElement.clientWidth + 'px';

	var center = new soso.maps.LatLng(lat, lon);
	var map = new soso.maps.Map(mapholder,{
		center: center,
		zoomLevel: 13
	});

	var geolocation = new soso.maps.Geolocation();
	var marker = null;
	geolocation.position({}, function(results, status) {
		console.log(results);
		var city = $("#info");
		if (status == soso.maps.GeolocationStatus.OK) {
			map.setCenter(results.latLng);
			domInfo.innerHTML = '你當前所在城市: ' + results.name;
		if (marker != null) {
			marker.setMap(null);
		}
		// 設定標記
		marker = new soso.maps.Marker({
			map: map,
			position:results.latLng
		});
		} else {
			alert("檢索沒有結果,原因: " + status);
		}
	});
}

測試結論:

1、Geolocation API的位置資訊來源包括GPS、IP地址、RFID、WIFI和藍芽的MAC地址、以及GSM/CDMS的ID等等。規範中沒有規定使用這些裝置的先後順序。
2、初測3g環境下比wifi環境理定位更準確;
3、測試三星 GT-S6358(android2.3) geolocation存在,但顯示位置資訊不可用POSITION_UNAVAILABLE。

六、把使用者捧在手心 – 環境光 Ambient Light簡介:

Ambient Light API定義了一些事件,這些時間可以提供源於周圍光亮程度的資訊,這通常是由裝置的光感應器來測量的。裝置的光感應器會提取出輝度資訊。

系統要求:

android firefox

測試例項:

核心程式碼:

這段程式碼實現感應用前當前環境光強度,調整網頁背景和文字顏色。

var domInfo = $('#info');
if (!('ondevicelight' in window)) {
	domInfo.innerHTML = '你的裝置不支援環境光Ambient Light API';
} else {
	var lightValue = document.getElementById('dl-value');
	window.addEventListener('devicelight', function(event) {
		domInfo.innerHTML = '當前環境光線強度為:' + Math.round(event.value) + 'lux';
		var backgroundColor = 'rgba(0,0,0,'+(1-event.value/100) +')';
		document.body.style.backgroundColor = backgroundColor;
		if(event.value < 50) {
			document.body.style.color = '#fff'
		} else {
			document.body.style.color = '#000'
		}
	});
}

思維發散:

該介面適合的範圍很窄,卻能做出很貼心的使用者體驗。

1、當我們根據Ambient Light強度、陀螺儀資訊、當地時間判斷出使用者正躺在床上準備入睡前在體驗我們的產品,我們自然可以調整我們背景與文字顏色讓使用者感覺到舒適,我們還可以來一段安靜的音樂,甚至使用Web Speech API播報當前時間,並說一聲“晚安”,何其溫馨;

2、該介面也可以應用於H5遊戲場景,比如日落時分,我們可以在遊戲中使用安靜祥和的遊戲場景;

3、當用戶在工作時間將手機放在暗處,偷偷地瞄一眼股市行情的時候,我們可以用語音大聲播報,“親愛的,不用擔心,你的股票中國中車馬上就要跌停了”,多美的畫面。