web-record1.php


Quell Code


<!doctype html>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Audio Recorder</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" media="all" href="https://netdna.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">

<style>
  
.control{
    background:blue;
    border-radius: 50%;
  position:absolute;
  z-index:1;
  top:10px;
  left:10px;
    width: 100px;
    height: 100px;
}

.fa{
  color:white;
  font-size:60px;
    position: absolute;
    top: 20px;
  left:30px;
    z-index: 1;
    transform: scale(0.9);

    cursor: pointer;
    transition: background-color 750ms;
}

.container {
    background:red;
    border-radius: 50%;
  top:10px;
  left:calc(70% - 65px);
  position:absolute;

    width: 120px;
    height: 120px;

}
#run{
 
  width:200px;
  height:30px;

  background:none;
  border:1px solid black;
}
#right{


}
#pro{
  width:0px;
  height:30px;
  color:black;
background:green;
  position:relative;
  display:inline-block;
  top:0;
  left:0;
}
.speech{
    animation: pulse 2.2s linear 33;
}
@keyframes pulse {
    0% {
       border:10px solid white;
    }
    25%{
       background:white;
    }
    75%{
       border:10px solid red;
    }
    100% {
       border:10px solid white;
       background:red;
    }
}

#prozent{
    position:relative;
    left:70px;
    z-index:3;
}

</style>
<script>
function drawBuffer( width, height, context, data ) {
    var step = Math.ceil( data.length / width );
    var amp = height / 2;
    context.fillStyle = "silver";
    context.clearRect(0,0,width,height);
    for(var i=0; i < width; i++){
        var min = 1.0;
        var max = -1.0;
        for (j=0; j<step; j++) {
            var datum = data[(i*step)+j]; 
            if (datum < min)
                min = datum;
            if (datum > max)
                max = datum;
        }
        context.fillRect(i,(1+min)*amp,1,Math.max(1,(max-min)*amp));
    }
}
</script>
<style>

canvas { 
		display: inline-block; 
		background: #202020; 
		box-shadow: 0px 0px 10px blue;
        height:100px;
        margin:5px;
        width:200px;
}
#record { height: 15vh; }
#record.recording { 
		background: red;
		background: -webkit-radial-gradient(center, ellipse cover, #ff0000 0%,lightgrey 75%,lightgrey 100%,#7db9e8 100%); 
		background: -moz-radial-gradient(center, ellipse cover, #ff0000 0%,lightgrey 75%,lightgrey 100%,#7db9e8 100%); 
		background: radial-gradient(center, ellipse cover, #ff0000 0%,lightgrey 75%,lightgrey 100%,#7db9e8 100%); 	}
#save, #save img { height: 10vh; }
#save { opacity: 0.25;}
#save[download] { opacity: 1;}

#viz{
        display:flex;
		flex-direction:row;
		justify-content: space-around;
		align-items: center;
}
#left,#right{
        display:flex;
        flex-dirction:column;
}

#server{
        position:relative;
        height:300px;
        overflow:auto;
        width:100%;
        border:2px solid black;
}
body{
        display:flex;
        flex-direction:column;
        font: 14pt Arial, sans-serif; 
    	background: lightgrey;
}
</style>
</head>
<body>
<h1>Press Micro to Record den Salat</h1>
<div id="viz">
    <div id="left">
		<canvas id="analyser" width="124" height="50"></canvas>
		<canvas id="wavedisplay" width="124" height="50"></canvas>
        <a id="save" href="#"><img src="save.svg"></a>
    </div>
    <div id="right">
        <div id="gogo" class="container">
            <div class="control">
                <div class="fa fa-microphone microphone-icon" id="record"  onclick="toggleRecording(this);"></div>
            </div>
        </div>
        <div id="viz1">
            <input type="hidden" id="tim" value="10">
            <div id="run">
                 <span id="pro">
                    <span id="prozent">0%</span>
                 </span>
            </div>
        </div>
    </div>
</div>
<div id="output"></div>
<div id="server"></div>
       
<script>
aktu();
function aktu(){
    $.ajax({
    	url: "lese.php",
		cache: false,
		success: function(res){
		     document.getElementById('server').innerHTML=res;
		},
	});
}
</script>
    
    
<script> 
(function(window){
  var WORKER_PATH = 'recorderWorker.js';
  var Recorder = function(source, cfg){
    var config = cfg || {};
    var bufferLen = config.bufferLen || 4096;
    this.context = source.context;
    if(!this.context.createScriptProcessor){
       this.node = this.context.createJavaScriptNode(bufferLen, 2, 2);
    } else {
       this.node = this.context.createScriptProcessor(bufferLen, 2, 2);
    }
   
    var worker = new Worker(config.workerPath || WORKER_PATH);
    worker.postMessage({
      command: 'init',
      config: {
        sampleRate: this.context.sampleRate
      }
    });
    var recording = false,
      currCallback;

    this.node.onaudioprocess = function(e){
      if (!recording) return;
      worker.postMessage({
        command: 'record',
        buffer: [
          e.inputBuffer.getChannelData(0),
          e.inputBuffer.getChannelData(1)
        ]
      });
    }

    this.configure = function(cfg){
      for (var prop in cfg){
        if (cfg.hasOwnProperty(prop)){
          config[prop] = cfg[prop];
        }
      }
    }

    this.record = function(){
      recording = true;
    }

    this.stop = function(){
      recording = false;
    }

    this.clear = function(){
      worker.postMessage({ command: 'clear' });
    }

    this.getBuffers = function(cb) {
      currCallback = cb || config.callback;
      worker.postMessage({ command: 'getBuffers' })
    }

    this.exportWAV = function(cb, type){
      currCallback = cb || config.callback;
      type = type || config.type || 'audio/wav';
      if (!currCallback) throw new Error('Callback not set');
      worker.postMessage({
        command: 'exportWAV',
        type: type
      });
    }

    this.exportMonoWAV = function(cb, type){
      currCallback = cb || config.callback;
      type = type || config.type || 'audio/wav';
      if (!currCallback) throw new Error('Callback not set');
      worker.postMessage({
        command: 'exportMonoWAV',
        type: type
      });
    }
    worker.onmessage = function(e){
      var blob = e.data;
      currCallback(blob);
    }
    source.connect(this.node);
    this.node.connect(this.context.destination);   // if the script node is not connected to an output the "onaudioprocess" event is not triggered in chrome.
  };
  Recorder.setupDownload = function(blob, filename){
    var url = (window.URL || window.webkitURL).createObjectURL(blob);
    var link = document.getElementById("save");
    link.href = url;
    link.download = filename || 'output.wav';
  }
  window.Recorder = Recorder;
})(window);
    
    </script>
	<script>
    
 
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var audioInput = null,
    realAudioInput = null,
    inputPoint = null,
    audioRecorder = null;
var rafID = null;
var analyserContext = null;
var canvasWidth, canvasHeight;
var recIndex = 0;

function saveAudio() {
    audioRecorder.exportWAV( doneEncoding );
    // audioRecorder.exportMonoWAV( doneEncoding );
}

function gotBuffers( buffers ) {
    var canvas = document.getElementById( "wavedisplay" );
    drawBuffer( canvas.width, canvas.height, canvas.getContext('2d'), buffers[0] );
    audioRecorder.exportWAV( doneEncoding );
}

function doneEncoding( blob ) {
            var fd = new FormData();
            fd.append('data', blob);
            $.ajax({
                method: 'POST',
                url: 'blob.php',
                data: fd,
                processData: false,
                contentType: false,
                success: function (output) {
                    console.log("done");
                    document.getElementById("output").innerHTML = output;
                    aktu();
                }
            });
    Recorder.setupDownload( blob, "myRecording" + ((recIndex<10)?"0":"") + recIndex + ".wav" );
    recIndex++;
}
  
micro=document.getElementById('gogo');
inpu=document.getElementById('tim');
proin=document.getElementById('pro');
proz=document.getElementById('prozent');
rec=document.getElementById('record');
micro.addEventListener('mousedown',function(e){
laufer=setInterval(function(){ toggleRecording(); }, 1000);
console.log('go animationund start record');
 
    if (rec.classList.contains("recording")) {
        audioRecorder.stop();
        rec.classList.remove("recording");
        audioRecorder.getBuffers( gotBuffers );
    } else {
        if (!audioRecorder)
            return;
        rec.classList.add("recording");
        audioRecorder.clear();
        audioRecorder.record();
    }
  document.getElementsByClassName('container')[0].classList.add('speech');
});


micro.addEventListener('mouseup',function(e){
  clearInterval(laufer);
  console.log('stop und sendentimer return auf 10');
  document.getElementsByClassName('container')[0].classList.remove('speech');
  inpu.value=10;
  proz.innerHTML='0%';
  proin.style.width='0px';
  if (rec.classList.contains("recording")) {
        audioRecorder.stop();
        rec.classList.remove("recording");
        audioRecorder.getBuffers( gotBuffers );
  }
})


lang=200;
function toggleRecording() {
  was=inpu.value;
  if(was>=1){
      was--;
      inpu.value=was;  
      was2=was*20;
      was1=lang-was2;
      proz.innerHTML=was1/2+'%';
      proin.style.width=was1+'px';
  }
}


function convertToMono( input ) {
    var splitter = audioContext.createChannelSplitter(2);
    var merger = audioContext.createChannelMerger(2);
    input.connect( splitter );
    splitter.connect( merger, 0, 0 );
    splitter.connect( merger, 0, 1 );
    return merger;
}

function cancelAnalyserUpdates() {
    window.cancelAnimationFrame( rafID );
    rafID = null;
}

function updateAnalysers(time) {
    if (!analyserContext) {
        var canvas = document.getElementById("analyser");
       canvasWidth = canvas.width;
        canvasHeight = canvas.height;
        analyserContext = canvas.getContext('2d');
    }

    // analyzer draw code here
    {
        var SPACING = 3;
        var BAR_WIDTH = 1;
        var numBars = Math.round(canvasWidth / SPACING);
        var freqByteData = new Uint8Array(analyserNode.frequencyBinCount);
        analyserNode.getByteFrequencyData(freqByteData); 
        analyserContext.clearRect(0, 0, canvasWidth, canvasHeight);
        analyserContext.fillStyle = '#F6D565';
        analyserContext.lineCap = 'round';
        var multiplier = analyserNode.frequencyBinCount / numBars;

        // Draw rectangle for each frequency bin.
        for (var i = 0; i < numBars; ++i) {
            var magnitude = 0;
            var offset = Math.floor( i * multiplier );
            for (var j = 0; j< multiplier; j++)
                magnitude += freqByteData[offset + j];
            magnitude = magnitude / multiplier;
            var magnitude2 = freqByteData[i * multiplier];
            analyserContext.fillStyle = "hsl( " + Math.round((i*360)/numBars) + ", 100%, 50%)";
            analyserContext.fillRect(i * SPACING, canvasHeight, BAR_WIDTH, -magnitude);
        }
    }
    rafID = window.requestAnimationFrame( updateAnalysers );
}

function toggleMono() {
    if (audioInput != realAudioInput) {
        audioInput.disconnect();
        realAudioInput.disconnect();
        audioInput = realAudioInput;
    } else {
        realAudioInput.disconnect();
        audioInput = convertToMono( realAudioInput );
    }
    audioInput.connect(inputPoint);
}

function gotStream(stream) {
    inputPoint = audioContext.createGain();
    realAudioInput = audioContext.createMediaStreamSource(stream);
    audioInput = realAudioInput;
    audioInput.connect(inputPoint);
// audioInput = convertToMono( input );
    analyserNode = audioContext.createAnalyser();
    analyserNode.fftSize = 2048;
    inputPoint.connect( analyserNode );
    audioRecorder = new Recorder( inputPoint );
    zeroGain = audioContext.createGain();
    zeroGain.gain.value = 0.0;
    inputPoint.connect( zeroGain );
    zeroGain.connect( audioContext.destination );
    updateAnalysers();
}

function initAudio() {
        if (!navigator.getUserMedia)
            navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
        if (!navigator.cancelAnimationFrame)
            navigator.cancelAnimationFrame = navigator.webkitCancelAnimationFrame || navigator.mozCancelAnimationFrame;
        if (!navigator.requestAnimationFrame)
            navigator.requestAnimationFrame = navigator.webkitRequestAnimationFrame || navigator.mozRequestAnimationFrame;

    navigator.getUserMedia(
        {
            "audio": {
                "mandatory": {
                    "googEchoCancellation": "false",
                    "googAutoGainControl": "false",
                    "googNoiseSuppression": "false",
                    "googHighpassFilter": "false"
                },
                "optional": []
            },
        }, gotStream, function(e) {
            alert('Error getting audio');
            console.log(e);
        });
}

window.addEventListener('load', initAudio );
    
</script>
</body>
</html>