0

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

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

4

1 回答 1

2

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

如果您开始录制 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();
    }
}

它应该解决这个问题。

于 2017-03-28T11:11:29.627 回答