让我彻底解释一下。我正在使用 Cordova 构建一个聊天应用程序,我想做一个录音功能,就像在 Messenger 中一样,你按住一个按钮,它会改变它的外观,然后在你释放按钮一段时间后,声音文件被发送到服务器。我尝试这样做,有时它可以工作,但有时它会意外停止,或者有时当您将手指移动一个像素时按钮的外观变为未单击。
现在这是我的按钮的 html
<ons-button id="btnRecordSound" modifier="large" disable-auto-styling>Hold to record</ons-button>
这是javascript
let soundRecord = '';
let isRecording = false;
function setRecordSoundButton() {
$('#btnRecordSound').on('touchstart touchend', (event) => {
if (event.type == 'touchstart') {
startSoundRecording();
} else if (event.type == 'touchend') {
stopSoundRecording();
}
});
}
function startSoundRecording() {
soundRecord = new Media(/*some file path here*/, () => {
// success function
});
soundRecord.startRecord();
isRecording = true;
setTimeout(favoChat.stopSoundRecording, 30000);
}
function stopSoundRecording() {
if (isRecording) {
isRecording = false;
soundRecord.stopRecord();
}
}
如您所见,我依靠 touchstart 和 touchend 事件来确定何时开始和停止它,并且还有一个强制 setTimeout 函数可以在给定的时间限制停止录制。
这是可视化按钮的最佳方式吗?我需要它在距离触摸点仅一像素时不改变外观。如果有的话,我想设置一些最大间隔,当移出它时,然后停止它。而且,启动和停止功能是否正常?我需要确切的停止功能。