【问题标题】:Javascript recorder and blob issueJavascript记录器和blob问题
【发布时间】:2019-03-12 00:11:15
【问题描述】:

关于录制的一切都很顺利,然后当您停止录制器时,文件会提供一个链接,您可以在其中上传。我的问题是当您点击停止按钮并且代码准备 BLOB 时,有没有办法将 BLOB wav 文件传输到 Wavesurfer-JS,以便它可以显示刚刚记录的波形文件,您可以编辑 wav 和亲眼所见?

我假设在“函数 createDownloadLink(blob)”部分下,我将捕获文件以发送到 Wavesurfer 以实时显示 Wav 文件?谢谢。

//App.JS

//webkitURL is deprecated but nevertheless
URL = window.URL || window.webkitURL;

var gumStream; 						//stream from getUserMedia()
var rec; 							//Recorder.js object
var input; 							//MediaStreamAudioSourceNode we'll be recording

// shim for AudioContext when it's not avb. 
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext //audio context to help us record

var recordButton = document.getElementById("recordButton");
var stopButton = document.getElementById("stopButton");
var pauseButton = document.getElementById("pauseButton");

//add events to those 2 buttons
recordButton.addEventListener("click", startRecording);
stopButton.addEventListener("click", stopRecording);
pauseButton.addEventListener("click", pauseRecording);

function startRecording() {
	console.log("recordButton clicked");

	/*
		Simple constraints object, for more advanced audio features see
		https://addpipe.com/blog/audio-constraints-getusermedia/
	*/
    
    var constraints = { audio: true, video:false }

 	/*
    	Disable the record button until we get a success or fail from getUserMedia() 
	*/

	recordButton.disabled = true;
	stopButton.disabled = false;
	pauseButton.disabled = false

	/*
    	We're using the standard promise based getUserMedia() 
    	https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
	*/

	navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
		console.log("getUserMedia() success, stream created, initializing Recorder.js ...");

		/*
			create an audio context after getUserMedia is called
			sampleRate might change after getUserMedia is called, like it does on macOS when recording through AirPods
			the sampleRate defaults to the one set in your OS for your playback device

		*/
		audioContext = new AudioContext();

		//update the format 
		document.getElementById("formats").innerHTML="Format: 1 channel pcm @ "+audioContext.sampleRate/1000+"kHz"

		/*  assign to gumStream for later use  */
		gumStream = stream;
		
		/* use the stream */
		input = audioContext.createMediaStreamSource(stream);

		/* 
			Create the Recorder object and configure to record mono sound (1 channel)
			Recording 2 channels  will double the file size
		*/
		rec = new Recorder(input,{numChannels:1})

		//start the recording process
		rec.record()

		console.log("Recording started");

	}).catch(function(err) {
	  	//enable the record button if getUserMedia() fails
    	recordButton.disabled = false;
    	stopButton.disabled = true;
    	pauseButton.disabled = true
	});
}

function pauseRecording(){
	console.log("pauseButton clicked rec.recording=",rec.recording );
	if (rec.recording){
		//pause
		rec.stop();
		pauseButton.innerHTML="Resume";
	}else{
		//resume
		rec.record()
		pauseButton.innerHTML="Pause";

	}
}

function stopRecording() {
	console.log("stopButton clicked");

	//disable the stop button, enable the record too allow for new recordings
	stopButton.disabled = true;
	recordButton.disabled = false;
	pauseButton.disabled = true;

	//reset button just in case the recording is stopped while paused
	pauseButton.innerHTML="Pause";
	
	//tell the recorder to stop the recording
	rec.stop();

	//stop microphone access
	gumStream.getAudioTracks()[0].stop();

	//create the wav blob and pass it on to createDownloadLink
	rec.exportWAV(createDownloadLink);
}

function createDownloadLink(blob) {
	
	var url = URL.createObjectURL(blob);
	var au = document.createElement('audio');
	var li = document.createElement('li');
	var link = document.createElement('a');

	//name of .wav file to use during upload and download (without extendion)
	var filename = new Date().toISOString();

	//add controls to the <audio> element
	au.controls = true;
	au.src = url;

	//save to disk link
	link.href = url;
	link.download = filename+".wav"; //download forces the browser to donwload the file using the  filename
	//add the new audio element to li
	li.appendChild(au);
	
	//add the filename to the li
	li.appendChild(document.createTextNode(filename+".wav "))

	//add the save to disk link to li
	li.appendChild(link);
	
	//upload link
	var upload = document.createElement('a');
	upload.href="#";
	upload.innerHTML = "Upload to server";
	upload.addEventListener("click", function(event){
		  var xhr=new XMLHttpRequest();
		  xhr.onload=function(e) {
		      if(this.readyState === 4) {
		          console.log("Server returned: ",e.target.responseText);
		      }
		  };
		
	var wavesurfer = WaveSurfer.create({
    container: '#waveform',
    waveColor: 'violet',
    progressColor: 'purple'
});
		wavesurfer.load(blob);
		
		  var fd=new FormData();
		  fd.append("audio_data",blob, filename);
		  xhr.open("POST","upload.php",true);
		  xhr.send(fd);
	})
	li.appendChild(document.createTextNode (" "))//add a space in between
	li.appendChild(upload)//add the upload link to li

	//add the li element to the ol
	recordingsList.appendChild(li);
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Simple Recorder.js demo with record, stop and pause</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
  <h1>Tester</h1>
  <br>
	  
<div id="controls">
  <button id="recordButton">Record</button>
  	 <button id="pauseButton" disabled>Pause</button>
  	 <button id="stopButton" disabled>Stop</button>
    </div>
    <div id="formats">Format: start recording to see sample rate</div>
  	<h3>Recordings</h3>
	<br>
  	<ol id="recordingsList"></ol>
	<br>
	<div id="waveform"></div>
	  
	  
    <!-- inserting these scripts at the end to be able to use all the elements in the DOM -->
	  
  <script src="https://cdn.rawgit.com/mattdiamond/Recorderjs/08e7abd9/dist/recorder.js"></script>
  <script src="js/app.js"></script>
  <script src="https://unpkg.com/wavesurfer.js"></script>
  </body>
</html>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    看起来 wavesurfer.js load 方法通过 XHR 加载,但有一个 loadBlob 方法接受 blob 或文件 URL。也许将wavesurfer.load(blob); 更改为wavesurfer.loadBlob(blob); 会产生更好的结果。

    【讨论】:

      【解决方案2】:

      如果您希望记录用户输入,请使用 MediaRecorder API:

        var constraints = { audio: true };
        var chunks = [];
      
        navigator.mediaDevices.getUserMedia(constraints)
          .then(function(stream) {
      
            var mediaRecorder = new MediaRecorder(stream);
      
            record.onclick = function() {
              mediaRecorder.start();
            }
      
            stop.onclick = function() {
              mediaRecorder.stop();
            }
      
            mediaRecorder.onstop = function(e) {
              var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
              chunks = [];
              var audioURL = URL.createObjectURL(blob);
              audio.src = audioURL;
            }
      
            mediaRecorder.ondataavailable = function(e) {
              chunks.push(e.data);
            }
      
          })
          .catch(function(err) {
            console.log('The following error occurred: ' + err);
          });
      

      【讨论】:

        猜你喜欢
        • 2018-07-16
        • 2016-11-09
        • 2014-10-10
        • 2013-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-13
        相关资源
        最近更新 更多