gpt4 book ai didi

javascript - Cordova - 用于“保持”录制音频的按钮 - 有时会停止

转载 作者:行者123 更新时间:2023-12-01 03:52:21 26 4
gpt4 key购买 nike

让我彻底解释一下。我正在使用 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 函数,可以在给定的时间限制内停止录制。

这是可视化按钮的最佳方式吗?我需要它在距离触摸点仅移动一个像素时不改变外观。如果有的话,我想设置一些最大间隔,当移动到它之外时,然后停止它。还有,启动和停止功能是否正常?我需要准确的停止功能。

最佳答案

我想它意外停止的原因是您在设置超时后没有清除超时。

如果您开始录制 20 秒的音频剪辑,停止录制,然后立即再次开始录制,仍然会有 10 秒的超时时间,因为它尚未被清除,并且将在 10 秒后运行。

如果您将代码更改为如下所示:

let soundRecord = '';
let isRecording = false;
let soundTimeout = null;

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;
soundTimeout = setTimeout(favoChat.stopSoundRecording, 30000);
}

function stopSoundRecording() {
if (isRecording) {
clearTimeout(soundTimeout);
isRecording = false;
soundRecord.stopRecord();
}
}

它应该可以解决这个问题。

关于javascript - Cordova - 用于“保持”录制音频的按钮 - 有时会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43067690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com