一键运行更多功能JavaScript(在浏览器中录制音频)

时间:2015-04-16 23:00:12

标签: javascript html audio

您好我有这个源代码在浏览器中录制音频。 Record.js调用另一个脚本,提供录制音频并将其保存到服务器。

的index.html

<button type="submit" onclick="toggleRecording()" data-run="0"></button>

record.js

//starts by click on button
  function toggleRecording() {
    var run = parseInt(getAttribute('data-run')); //

      if(run === 1) {
      recorder && recorder.stop();
      recorder && recorder.exportWAV(function(blob) {
        uploadAudioFromBlob(blob);
      });
      __log('Recording is  stopped.');
      button.setAttribute('data-run', 0);

    } 

    else {
      recorder && recorder.clear();
      recorder && recorder.record();
      __log('Speak...');
      button.setAttribute('data-run', 1);
    }
  }

  function __log(e, data) {     
showInfo("\n" + e + " " + (data || ''));  
  }

  var audio_context;
  var recorder;
  function startUserMedia(stream) { 
    var input = audio_context.createMediaStreamSource(stream); 
    recorder = new Recorder(input); 
    __log('Systém for recording is available.'); 
  }

  function startRecording(button) {   
    recorder && recorder.clear(); 
    recorder && recorder.record(); 
    button.nextElementSibling.disabled = false;
    __log('Talk...'); 
  }

   window.onload=function init() {
    try { 
      window.AudioContext = window.AudioContext || window.webkitAudioContext; 
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;   
      window.URL = window.URL || window.webkitURL;      
      audio_context = new AudioContext;      
    } catch (e) { 
      alert('This browser do not support audio!');
    }    
    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
      __log('No audio was detected: ' + e);
    });
  };

现在,此录制系统按以下步骤操作:

  1. function init()在加载页面时立即运行,并且用户允许在消息startusermedia函数中运行麦克风 2点击按钮后运行toggleRecording(button)功能开始录制音频
  2. 第二次点击按钮运行toggleRecording功能,停止录制音频
  3. 如果有可能,我想在此步骤中使用此系统: 1.首先点击按钮运行功能“init”和“startusermedia”和“togglerecording”,以便点击后立即开始录制 2.点击将调用“toggleRecording”功能停止录制

    此主题与我之前的问题相关:Run 2 functions with one button Javascript

1 个答案:

答案 0 :(得分:0)

如果我正确地提出您的问题,您只需要这样的事情:

var recording = false;
var recordButton = document.getElementById('recordButton');
function startRecording() {
   if(!recording)
   {
      init();
      startusermedia(recordButton); 
  }

  toggleRecording(recordButton);
  recording = !recording;

}

按钮:

<button type="submit" onclick="startRecording();" data-run="0" id="recordButton"></button>