如何修改此Javascript以使其在没有任何html代码的情况下工作?

时间:2018-11-04 18:27:48

标签: javascript html

我找到了在浏览器中记录声音的Javascript代码。它由HTML代码和Javascript代码组成,这是我的问题,因为我只想要没有HTML代码的Javascript代码。 如何将此代码转换为纯Javascript以在 Storyline 中使用? 在 Storyline 中,我有两个按钮,分别名为“ 开始”和“ 停止”,以执行Javascript,就像下面的代码一样。

如何摆脱HTML代码并仍然进行录音?

HTML代码:

<body>
    <div>
        <h2>Audio record and playback</h2>
        <p>
            <button id=startRecord>start</button>
            <button id=stopRecord disabled>stop</button>
        </p>    
        <p>
            <audio id=recordedAudio></audio>
            <a id=audioDownload></a>
        </p>
    </div>
</body>

JavaScript代码:

navigator.mediaDevices.getUserMedia({audio:true})
.then(stream => {
    rec = new MediaRecorder(stream);
    rec.ondataavailable = e => {
        audioChunks.push(e.data);
        if (rec.state == "inactive"){
            let blob = new Blob(audioChunks,{type:'audio/x-mpeg-3'});
            recordedAudio.src = URL.createObjectURL(blob);
            recordedAudio.controls=true;
            recordedAudio.autoplay=true;
            audioDownload.href = recordedAudio.src;
            audioDownload.download = 'mp3';
            audioDownload.innerHTML = 'download';
        }
    }
})
.catch(e=>console.log(e));

startRecord.onclick = e => {
    startRecord.disabled = true;
    stopRecord.disabled=false;
    audioChunks = [];
    rec.start();
}

stopRecord.onclick = e => {
    startRecord.disabled = false;
    stopRecord.disabled=true;
    rec.stop();
}

这是链接:

https://jsfiddle.net/sasivarunan/bv55z5fe/

1 个答案:

答案 0 :(得分:0)

您可以让您的JavaScript创建DOM元素,以便您的解决方案需要零修改的HTML,尽管这似乎有点令人费解:

;(function() {
  let audioChunks = []

  const startRecord = document.getElementById('startRecord')
  const stopRecord = document.getElementById('stopRecord')
  startRecord.addEventListener('click', () => {
    startRecord.disabled = true
    stopRecord.disabled = false
    audioChunks = []
    rec.start()
  })

  stopRecord.addEventListener('click', () => {
    startRecord.disabled = false
    stopRecord.disabled = true
    rec.stop()
  })

  const recordedAudio = document.createElement('audio')
  document.body.appendChild(audio)

  navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then(stream => {
      rec = new MediaRecorder(stream)
      rec.ondataavailable = e => {
        audioChunks.push(e.data)
        if (rec.state == "inactive") {
          let blob = new Blob(audioChunks, { type: "audio/x-mpeg-3" })
          recordedAudio.src = URL.createObjectURL(blob)
          recordedAudio.controls = true
          recordedAudio.autoplay = true
          audioDownload.href = recordedAudio.src
          audioDownload.download = "mp3"
          audioDownload.innerHTML = "download"
        }
      }
    })
    .catch(e => console.log(e))
})()