problems stopping audio recording API MediaRecorder

I have an application that uses MediaRecorder to record the audio of the calls, but it has some recordings that get stuck and are repeated for other calls, or it simply cuts the audio in half.

The start recording function:

function gravacaoAudio() {
console.log(“Gravação de Audio Iniciada”);

mediaOptions = {
    tag: 'audio',
    tipo: 'audio/mpeg',
    ext: '.mp3',
    opcao: { audio: true }
};

navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; 
if (navigator.getMedia) {
    navigator.getMedia({ audio: true, video: false }, function (stream) {
        if (navigator.userAgent.toLowerCase().search("edge") === -1 || navigator.userAgent.toLowerCase().search("msie") === -1) {
            recorder = new MediaRecorder(stream);
            recorder.ondataavailable = e => {
                partes.push(e.data);
                if (recorder.state === 'inactive') {
                    //Finalizo o atendimento

                    let idSenha = $('#hdnIdSenha').val();

                    if (idSenha != "") {
                        FinalizarAtendimento(servicosSelecionados, strChaveControle, strChaveControleComentario);
                    } else {
                        $("#chamarSenha").prop('disabled', false);

                        clearInterval(intervaloRelogioAoVivo);
                        clearInterval(intervaloCancelarAoVivo);
                        audioAoVivo('AGUARDANDO INÍCIO DE UM NOVO ATENDIMENTO...');
                    }
                    
                }
            };
        } else {

            audioAoVivoRemover('GRAVAÇÃO INDISPONÍVEL - PROBLEMA COM O NAVEGADOR');
        }
    }, function () {
        audioAoVivoRemover('GRAVAÇÃO INDISPONÍVEL - CALLBACK AUDIO');
    });
}
else {
    audioAoVivoRemover('GRAVAÇÃO INDISPONÍVEL - USE MEDIA');
}

}

And the stop recording function:

function StopGravacao() {

if (typeof recorder === "undefined") {
    //Finalizo o atendimento caso não exista gravacao de audio

    bootbox.alert("Não é possível finalizar o atendimento até que a gravação de áudio fique disponível, favor verifiquei o dispositivo de áudio!");

    //FinalizarAtendimento(servicosSelecionados, strChaveControle, strChaveControleComentario);
} else {
   
    screenStream.getTracks().forEach((track) =>
        screenStream.getTracks().forEach((track) =>
            voiceStream.getAudioTracks().forEach((audio) => audio.stop());
            if (recorder) {
                recorder.stop();
                $('.time').hide(); 
            }
            recorder = null;
        })
    );
}    

}