UPDATE: 這篇博文已經過期, 新的BUG總結請看微信JSSDK與錄音相關的坑
微信JSSDK有不少坑, 最近做一個webapp, 用到了其中的錄音功能, 發現不少問題, 總結一下:
當你調用startRecord和stopRecord的時間間隔過於短時, stopRecord調用會失敗, 但是不會觸發success, fail或complete中的任何一個Handler, 導致UI卡住.
我的解決方法是: startRecord調用成功后500ms才可以調用stopRecord, 如果在500ms之內就執行了endRecord, 則判定為過早的endRecord, 執行failHandler, 隨后每隔300ms調用一次endRecord, 直至endRecord調用成功.
function delayedStopRecord(options) {
stopRecord(options);
setTimeout(function () {
if (!self.canStartRecord) {
delayedStopRecord(options);
}
}, 300);
}
self.startRecord = function (options) {
if (!self.canStartRecord) return;
options.success = options.success || $.noop;
options.fail = options.fail || $.noop;
options.complete = options.complete || $.noop;
self.canStartRecord = false;
self.canStopRecord = false;
var s1 = options.success;
options.success = function () {
s1();
setTimeout(function () {
self.canStopRecord = true;
}, 500);
}
var fail = options.fail;
options.fail = function (res) {
fail();
self.canStartRecord = true;
}
var s2 = options.success;
options.success = function () {
s2();
wx.onVoiceRecordEnd({
complete: options.onRecordTimeout
});
}
wx.startRecord(options);
}
self.endRecord = function (options) {
options.success = options.success || $.noop;
options.fail = options.fail || $.noop;
options.complete = options.complete || $.noop;
var complete = options.complete;
options.complete = function () {
complete();
self.canStartRecord = true;
}
if (!self.canStopRecord) {
// Fix for too short stop record call failure.
// Can only stop record after 500 ms. Before 500ms, it's a premature endRecord call.
// For a premature endRecord call, try stop record every 300ms.
options.fail({ errMsg: 'stopRecord:tooshort' }); // Manually call failHandler.
options.abort = true;
delayedStopRecord(options);
} else {
stopRecord(options);
}
}
function init() {
// Initialize flags.
self.canStartRecord = true; // True if this is the first call or the last stopRecord succeeded.
self.canStopRecord = false;
}
其中stopRecord函數封裝了wx.stopRecord和wx.uploadVoice, init是viewModel的初始化函數.
的確感受到了寫作的好處, 在這里這段代碼的過程中我還調整了代碼的位置讓代碼的邏輯更加清晰了. 繼續加油!
其他發現的一些bug, 暫時還沒解決.
iPhone:
錄音中按home返回主菜單, 錄音中斷, 回到微信, 此時endRecord會失敗因為並沒有在錄音, 需要調用startRecord.
Android:
錄音中按home返回主菜單, 錄音繼續, 回到微信可以正常endRecord
iPhone:
錄音中關閉webapp, 錄音結束, 回到webapp可以正常啟動錄音.
Android:
錄音中關閉webapp, 錄音繼續, 回到webapp調用startRecord會失敗提示recording.
iPhone:
錄音中刷新webapp, 無法調用startRecord.
Android:
沒有刷新按鈕所以沒這個問題.
