|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  AutoIt (Programación) Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  Teleco - Emisora de A.M. Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

App inventor 2 en español
Cómo programar los teléfonos móviles con Android.
Curso de App inventor 2 en español - Juan Antonio Villalpando

-- Tutorial de iniciación de App Inventor 2 en español --

Volver al índice del tutorial

___________________________

169Q.- Analizador de archivo de sonido. FFT. Espectro. VU. JavaScript.

1.- p169Q_javascript_FFT.aia

- Se vería así:

- Tenemos un archivo de sonido y vamos a oirlo viendo su espectro de frecuencia.

- Estos ejemplos funcionan con archivos de sonido. No funciona con micrófono ni con el sonido directo.

- FFT significa Transformada Rápida de Fourier, es un procedimiento matemático por el cual podemos descomponer las señales en una serie de ondas senoidales, cada una caracterizada por su amplitud y su frecuencia. La suma de esas ondas daría la señal inicial.

- FFT se utiliza para analizar sonidos, imágenes, modulaciones,...

- Nos basamos en el código JavaScript obtenido en:

http://www.smartjava.org/content/exploring-html5-web-audio-visualizing-sound

- Utilizaremos la extensión: com.KIO4_Explorer.aix que utilizamos como Explorador de archivos.

- El listado de archivos se mostrará en un VisorDeLista.

- Los archivos de música se suelen almacenar en el móvil, en el directorio:

/mnt/sdcard/Music

que es el mismo que:

/storage/sdcard0/Music

_________________
- Diseño.

com.KIO4_Explorer.aix

jquery-1.8.0.min.js

sonido.htm

_________________
- Bloques.

file:///mnt/sdcard/AppInventor/assets/sonido.htm

_________________
- Archivo. JavaScript.

sonido.htm
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<head>
    <title>Loading and playing a sound with the Web Audio API</title>
    <script type="text/javascript" src="jquery-1.8.0.min.js"></script>
</head>
<body style="background-color: white;">

<canvas id="canvas" width="600" height="300" style="display: block;"></canvas>

<script type="text/javascript">

    sonido =  window.AppInventor.getWebViewString(); // Entrada de datos.

    // create the audio context (chrome only for now)
    if (! window.AudioContext) {
        if (! window.webkitAudioContext) {
            alert('no audiocontext found');
        }
        window.AudioContext = window.webkitAudioContext;
    }
    var context = new AudioContext();
    var audioBuffer;
    var sourceNode;
    var analyser;
    var javascriptNode;

    // get the context from the canvas to draw on
    var ctx = $("#canvas").get()[0].getContext("2d");

    // create a gradient for the fill. Note the strange
    // offset, since the gradient is calculated based on
    // the canvas, not the specific element we draw
    var gradient = ctx.createLinearGradient(0,0,0,300);
    gradient.addColorStop(1,'#000000');
    gradient.addColorStop(0.75,'#ff0000');
    gradient.addColorStop(0.25,'#ffff00');
    gradient.addColorStop(0,'#ffffff');

    // load the sound
    setupAudioNodes();
    //loadSound("wagner-short.ogg");
	loadSound(sonido);

    function setupAudioNodes() {

        // setup a javascript node
        javascriptNode = context.createScriptProcessor(2048, 1, 1);
        // connect to destination, else it isn't called
        javascriptNode.connect(context.destination);

        // setup a analyzer
        analyser = context.createAnalyser();
        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 512;

        // create a buffer source node
        sourceNode = context.createBufferSource();
        sourceNode.connect(analyser);
        analyser.connect(javascriptNode);

        sourceNode.connect(context.destination);
    }

    // load the specified sound
    function loadSound(url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';

        // When loaded decode the data
        request.onload = function() {

            // decode the data
            context.decodeAudioData(request.response, function(buffer) {
                // when the audio is decoded play the sound
                playSound(buffer);
            }, onError);
        }
        request.send();
    }

    function playSound(buffer) {
        sourceNode.buffer = buffer;
        sourceNode.start(0);
    }

    // log if an error occurs
    function onError(e) {
        console.log(e);
    }

    // when the javascript node is called
    // we use information from the analyzer node
    // to draw the volume
    javascriptNode.onaudioprocess = function() {

        // get the average for the first channel
        var array =  new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(array);

        // clear the current state
        ctx.clearRect(0, 0, 600, 300);

        // set the fill style
        ctx.fillStyle=gradient;
        drawSpectrum(array);

    }

    function drawSpectrum(array) {
        for ( var i = 0; i < (array.length); i++ ){
            var value = array[i];

            ctx.fillRect(i*5,300-value,3,300);
            //  console.log([i,value])
        }
    };

</script>

</body>
</html> 

__________________________________
__________________________________
__________________________________
__________________________________
- VU metro.

2.- p169Q_javascript_FFT_VU.aia

- Se vería así:

_________________
- Diseño.

com.KIO4_Explorer.aix

jquery-1.8.0.min.js

sonido2.htm

_________________
-
Bloques.

_________________
- Archivo. JavaScript.

sonido2.htm
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<head>
    <title>Loading and playing a sound with the Web Audio API</title>
    <script type="text/javascript" src="jquery-1.8.0.min.js"></script> 
</head>
<body>
<canvas id="canvas" width="60" height="130" style="display: block;"></canvas>

<script type="text/javascript">
    // Modificado por Juan A. Villalpando
    sonido =  window.AppInventor.getWebViewString(); // Entrada de datos.

    // create the audio context (chrome only for now)
    if (! window.AudioContext) {
        if (! window.webkitAudioContext) {
            alert('no audiocontext found');
        }
        window.AudioContext = window.webkitAudioContext;
    }
    var context = new AudioContext();
    var audioBuffer;
    var sourceNode;
    var splitter;
    var analyser, analyser2;
    var javascriptNode;

    // get the context from the canvas to draw on
    var ctx = $("#canvas").get()[0].getContext("2d");

    // create a gradient for the fill. Note the strange
    // offset, since the gradient is calculated based on
    // the canvas, not the specific element we draw
    var gradient = ctx.createLinearGradient(0,0,0,130);
    gradient.addColorStop(1,'#000000');
    gradient.addColorStop(0.75,'#ff0000');
    gradient.addColorStop(0.25,'#ffff00');
    gradient.addColorStop(0,'#ffffff');

    // load the sound
    setupAudioNodes();
    loadSound(sonido); // Aqui carga el sonido.
	
    function setupAudioNodes() {

        // setup a javascript node
        javascriptNode = context.createScriptProcessor(2048, 1, 1);
        // connect to destination, else it isn't called
        javascriptNode.connect(context.destination);


        // setup a analyzer
        analyser = context.createAnalyser();
        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 1024;

        analyser2 = context.createAnalyser();
        analyser2.smoothingTimeConstant = 0.0;
        analyser2.fftSize = 1024;

        // create a buffer source node
        sourceNode = context.createBufferSource();
        splitter = context.createChannelSplitter();

        // connect the source to the analyser and the splitter
        sourceNode.connect(splitter);

        // connect one of the outputs from the splitter to
        // the analyser
        splitter.connect(analyser,0,0);
        splitter.connect(analyser2,1,0);

        // connect the splitter to the javascriptnode
        // we use the javascript node to draw at a
        // specific interval.
        analyser.connect(javascriptNode);

//        splitter.connect(context.destination,0,0);
//        splitter.connect(context.destination,0,1);

        // and connect to destination
        sourceNode.connect(context.destination);
    }

    // load the specified sound
    function loadSound(url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';

        // When loaded decode the data
        request.onload = function() {

            // decode the data
            context.decodeAudioData(request.response, function(buffer) {
                // when the audio is decoded play the sound
                playSound(buffer);
            }, onError);
        }
        request.send();
    }


    function playSound(buffer) {
        sourceNode.buffer = buffer;
        sourceNode.start(0);
    }

    // log if an error occurs
    function onError(e) {
        console.log(e);
    }

    // when the javascript node is called
    // we use information from the analyzer node
    // to draw the volume
    javascriptNode.onaudioprocess = function() {

        // get the average for the first channel
        var array =  new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(array);
        var average = getAverageVolume(array);

        // get the average for the second channel
        var array2 =  new Uint8Array(analyser2.frequencyBinCount);
        analyser2.getByteFrequencyData(array2);
        var average2 = getAverageVolume(array2);

        // clear the current state
        ctx.clearRect(0, 0, 60, 130);

        // set the fill style
        ctx.fillStyle=gradient;

        // create the meters
        ctx.fillRect(0,130-average,25,130);
        ctx.fillRect(30,130-average2,25,130);
		 // Modificado por Juan A. Villalpando
		window.AppInventor.setWebViewString("" + average + "|" + average2);  // Respuesta a CadenaDeWebView
    }

    function getAverageVolume(array) {
        var values = 0;
        var average;

        var length = array.length;

        // get all the frequency amplitudes
        for (var i = 0; i < length; i++) {
            values += array[i];
        }

        average = values / length;
        return average;
    }

</script>

</body>
</html>

__________________________________
__________________________________
__________________________________
__________________________________

3.- Obtener el nivel de sonido del micrófono del ordenador mediante una página web.

- Entramos en esta página web con el navegador Chrome.

- Ponemos un micrófono en nuestro ordenador.

- Permitimos el uso del micrófono en Chrome.

- Observamos el nivel de sonido cuando hablamos por el micrófono.

- sonido4.htm

- Baja este archivo a tu ordenador y ábrelo con el navegador Chrome.

- Puedes subir el archivo a un hosting, pero debe ser https:// (no funciona con http://).

- Since last year, to use the microphone you'll need to use a https connection.

- Código de: https://codepen.io/huooo/pen/xJNPOL

sonido4.htm
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<style>
.container{width:80%;min-height: 400px;margin:0 auto;overflow: hidden;}
.font-c-light{color:#aaa;}
.header, .footer{width:100%;text-align:center;}
a{text-decoration:none;color:rgba(230,0,0,1)}
</style>

<div class="container">
  <p>Valor del volumen <span id="audio-value">null</span></p>
</div>
</head>

<body  onload="beginDetect()">

<script type="text/javascript">
var audioContext = new (window.AudioContext || window.webkitAudioContext)()
var mediaStreamSource = null
var meter = null

function beginDetect() {
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => {
      mediaStreamSource = audioContext.createMediaStreamSource(stream)
      meter = createAudioMeter(audioContext)
      mediaStreamSource.connect(meter)
    })
  }
}

__________________________________
__________________________________
__________________________________
__________________________________

4.- Reconocedor de voz.

- Abrimos este archivo con el navegador Chrome.

- Pulsamos el icono del micrófono. Hablamos delante del micrófono del ordenador.

- Reconocerá la frase que hemos pronunciado. Abrirá el Google y buscará esa frase en internet.

- sonido5.htm

- Baja este archivo a tu ordenador y ábrelo con el navegador Chrome.

- Puedes subir el archivo a un hosting, pero debe ser https:// (no funciona con http://).

- Código de: https://www.labnol.org/software/add-speech-recognition-to-website/19989/

- Otra página: https://www.google.com/intl/en/chrome/demos/speech.html

- Vocoder: https://webaudiodemos.appspot.com/Vocoder/index.html#

sonido5.htm
 
<!-- CSS Styles -->
<style>
  .speech {border: 1px solid #DDD; width: 300px; padding: 0; margin: 0}
  .speech input {border: 0; width: 240px; display: inline-block; height: 30px;}
  .speech img {float: right; width: 40px }
</style>

<!-- Search Form -->
<form id="labnol" method="get" action="https://www.google.com/search">
  <div class="speech">
    <input type="text" name="q" id="transcript" placeholder="Pulsa el icono del microfono y habla." />
	<br><br><br><br>
    <img src="http://juanant91.byethost3.com/microfono.gif" width="50" height="50" onclick="startDictation()" />
  </div>
</form>

<!-- HTML5 Speech Recognition API -->
<script>
  function startDictation() {

    if (window.hasOwnProperty('webkitSpeechRecognition')) {

      var recognition = new webkitSpeechRecognition();

      recognition.continuous = false;
      recognition.interimResults = false;

      // recognition.lang = "en-US"; // English
	  recognition.lang = "es-ES"; // Español
      recognition.start();

      recognition.onresult = function(e) {
        document.getElementById('transcript').value
                                 = e.results[0][0].transcript;
        recognition.stop();
        document.getElementById('labnol').submit();
      };

      recognition.onerror = function(e) {
        recognition.stop();
      }

    }
  }
</script>

__________________________________

 

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información