AudioResearchBlog

Covering all audio related stuff with special focus on programming and digital signal processing

Archive for the 'math' Category

Some experience with CLAM inside an audio club at FIUBA, Argentina

Posted by hordia on 11th March 2010

(Note: I wrote this as something to tell to the clam-devel mailing list about some of my source-code commits)

About eight months ago, there was a foundation of something like an “audio club” in my university [1]. As soon i learned about that, i quickly got in touch with them and noticed that there was a major interest in analog issues (the only audio area with at least elective, courses in the university). So i told them about all the cool things that are available and ready to do with digital audio, mostly signal processing related. I talked in general, but of course i also talked about clam, with all its prototyping, real-time and easy development of plugins features. Even many of them ended installing and using it, and some even developing with more or less help. One thing to notice is that most of them are students from first years and most (but not all) are students with a basic programming level (because they are from electronics) but strong dsp knowledge (behind this is an university with more emphasis in theory than practice)
We started specifying plugins from a more abstract level (inputs/outputs/controls) and generating the source code base using
CLAM’s Templated Plugins Code Generator [2] and prototyping some simple applications. But one of the things we ended up doing was to take advantage of clam as platform to prototype medic related applications like filter ECG signal from noise in realtime, and some like _vice-versa_, i mean applying some processing knowledge from that area to audio.

Some of that work (one hour per week average) it’s now in the repo, most remarkable i think are filters work, by above the adaptative notch one (which even was used as a demo of a talk of one of the members about the steepest descent algorithm and its application to filter ECG signals)

Some development screenshots:
http://clam-project.org/wiki/Image:FilterByCoefExample.jpg
http://clam-project.org/wiki/Image:FilterExample-LP-HP.jpg
http://clam-project.org/wiki/Image:ThreeBandFilterOutputWithWhiteNoiseAsInput.jpg
http://clam-project.org/wiki/Image:GaussianWhiteNoiseHistogram.jpg
http://clam-project.org/wiki/Image:UniformWhiteNoiseHistogram.jpg

[0] FIUBA: Engineering Faculty of Buenos Aires University
[1] Group: http://code.google.com/p/club-audio-fiuba
Source code repo: http://groups.google.com/group/club_de_audio_fiuba
[2] http://audiores.uint8.com.ar/blog/2009/08/17/showing-a-little-about-clam-as-a-prototyping-tool-at-the-audio-club-of-fiuba/


, , , , , , , , , , , , , , , , , , ,

Posted in audio, algorithms, effects, signal processing, free software, programming, matlab, GPL, c++, blog, noise, python, projects, math, English, CLAM, news, plugins, ideas, ClubAudioFiuba | No Comments »

Fundamental (in Hz) to a MIDI note

Posted by hordia on 26th August 2007

Working to have audio-to-midi in NetworkEditor (CLAM) I needed to convert a fundamental frequency value to a MIDI note one.

I found some source code related with this in Voice2MIDI app, but was not explained at all, so looking for the reason of that formula I arrived at this:

Knowing about equal-tempered scale (check this) and 2^{\frac{n}{12}} relation between frequencies plus the fact that C4 or “middle c” has a MIDI value of 60, it’s easy to conclude that then A4 (which its frequency value is 440Hz, a standard for tunning and is 9 semi-tones more) has a MIDI value of 69.

 

Then, starting with:
fundfrec = 440Hz * 2^{(\frac{1}{12})^n}

 

It’s easy to arrive at this:
fund_{midinote} = 69+log_{2^{(\frac{1}{12})}}(\frac{fundfrec}{440Hz})

 

and then, also taking in account this mathematical relation::
log_{2^{\frac{1}{12}}}(a) = log_{e}(a)*17.31234

 

the final formula looks like:
fund_{midinote} = 69+log_{e}(\frac{fundfrec}{440Hz})*17.31234

 

and a final c++ code like:

fund_midinote = round( 69. + log(fundfrec/440.)*17.31234 );

 
Related post: nictuku’s inverse formula (i.e. from MIDI to Hz) here “Translanting MIDI Notes to frequencies in the diatonic scale using the central A (440hz) as reference“.


, , , , , , , , , ,

Posted in audio, algorithms, programming, music theory, c++, midi, math, English, CLAM, standards, GSoC2007 | No Comments »

SMS Harmonizer part1

Posted by hordia on 31st July 2007

I’ll start talking a bit about this effect which is mainly used for vocal harmonizing. Given an input voice (or whatever) as output you obtain (how many as you want) automatic harmonic related voices (a minor/major third, a fifth, a sixth or any musical interval you want).

This implementation, is mainly based on many SMS pitch-shiftings (one for each voice) and a control gain for each one. Pitch controls are based on equal-tempered scale semitones, following fund*2^{\frac{p_c}{12}} relation for each voice.

 
This was my first version of the network:

SMSHarmonizer-basic-network

 
 
Testing it, my voice never sounded so musical, hehehe… but still awful, so I was thinking in your ears health and demos are with Elvis one ;-)

Disclaimer: all audio demos are early testing versions (still with artifacts and clicks that should be removed soon)

Elvis harmonized demo: elvis-harmonized.ogg (to hear the online/streaming version go here)

 
Prototype:

harmonizer prototype

 
 
Configuration:
SMSHarmonizer config

Note: demos were done without residual processing because adding residual does not improve results much and adds a lot of overhead.

 
 
Then, following xamat’s suggestions I also added a detunning effect (and delay, but this one isn’t working properly yet)

SMSHarmonizer detuning delay

 
 
Elvis harmonized (detunned version) demo: elvis-harmonized-detunned.ogg (to hear the online/streaming version go here)

 
but wait! a lot of graphics and this is also a ‘coding’ blog!!! here you have some code… and btw you can see that programming under CLAM could be very easy once you get the basics…

bool SMSHarmonizer::Do( const SpectralPeakArray& inPeaks, 
			const Fundamental& inFund,
			const Spectrum& inSpectrum, 
			SpectralPeakArray& outPeaks,
			Fundamental& outFund,
			Spectrum& outSpectrum
		      )
{
	outPeaks = inPeaks;
	outFund = inFund;
	outSpectrum = inSpectrum;
 
	TData gain0 = mInputVoiceGain.GetLastValue();
	mSinusoidalGain.GetInControl("Gain").DoControl(gain0);
	mSinusoidalGain.Do(outPeaks,outPeaks);
 
	SpectralPeakArray mtmpPeaks;
	Fundamental mtmpFund;
	Spectrum mtmpSpectrum;
 
	for (int i=0; i < mVoicesPitch.Size(); i++)
	{
		TData gain = mVoicesGain[i].GetLastValue();
		if (gain&lt;0.01) //means voice OFF
			continue;
		
		TData amount = mVoicesPitch[i].GetLastValue() + frand()*mVoicesDetuningAmount[i].GetLastValue(); //detuning
		amount = CLAM_pow( 2., amount/12. ); //adjust to equal-tempered scale semitones
 
		mPitchShift.GetInControl("PitchSteps").DoControl(amount);
		mPitchShift.Do( inPeaks,
				inFund, 
				inSpectrum,
				mtmpPeaks, 
				mtmpFund,
				mtmpSpectrum);
	
		mSinusoidalGain.GetInControl("Gain").DoControl(gain);
		mSinusoidalGain.Do(mtmpPeaks,mtmpPeaks);
 
		TData delay = mVoicesDelay[i].GetLastValue();
		if (delay>0.)
		{
			mPeaksDelay.GetInControl("Delay Control").DoControl(delay);
			mPeaksDelay.Do(mtmpPeaks, mtmpPeaks);
		}
 
		outPeaks = outPeaks + mtmpPeaks;
		
		if (!mIgnoreResidual)
			mSpectrumAdder.Do(outSpectrum, mtmpSpectrum, outSpectrum);
	}
	return true;
}

The plan includes add MIDI control for each voice pitch (then will be easy to control them for example by a keyboard by the same singing person)

Next post: SMSMorph.


, , , , , , , , , , , ,

Posted in audio, algorithms, effects, signal processing, programming, music theory, c++, midi, math, English, CLAM, GSoC2007, GUI | 1 Comment »

Construir un instrumento de teclado temperado según el sistema Mercator

Posted by hordia on 10th April 2007

Hace un tiempo, se contactó conmigo una persona que me pidió si lo podía poner en contacto con gente que pudiese llegar a interesarse en construir un instrumento de teclado temperado según el sistema Mercator o escala temperada que tenga los conocimiento necesarios como para llevarlo a cabo (la idea era/es armar un mini-grupo de trabajo).

Básicamente:

“La propuesta del presente trabajo es construir un instrumento musical de teclado temperado según la convergente (53 / 31) (ver: Federico Miyara: “La música de las esferas: de Pitágoras a Xenakis… y más acá“). Este temperamento parece adjudicado al célebre matemático Mercator. Del libro “Acústica musical y organología”, Tirso de Olazábal, Editorial Ricordi Americana, 1977, extraigo el siguiente fragmento:”El intento más ingenioso ha sido realizado por el famoso matemático Gerardo Mercator, que propuso en el siglo XVI un sistema basado sobre una sucesión de 53 quintas, que origina una coma pequeñísima; este sistema, llamado a veces “sistema de los 53 grados”, permite obtener quintas y terceras mayores casi perfectas. En el siglo pasado fueron construidos dos órganos con 53 teclas por octava, templados según el sistema de Mercator, pero no tuvieron éxito debido a su enorme dificultad de ejecución.” Para simplificar, llamaré a este sistema “sistema Mercator”, “temperamento Mercator” o “escala Mercator”. Básicamente este temperamento consiste en dividir la octava en 53 “microtonos” iguales entre sí, y usar estos microtonos para obtener los tonos y semitonos de la escala natural con una gran aproximación” (sigue)

El documento completo que me envió se encuentra aca: “Instrumento musical de teclado temperado según el sistema Mercator” (recomiendo su lectura completa)

Por mi parte, en este momento no cuento con mucho tiempo libre debido al trabajo, facultad y otros proyectos, pero me ofrecí a ayudarlo en lo que pudiera y tratar de ponerlo en contacto con gente a la que le pudiera interesar la idea. Ese es uno de los objetivos de este post, darle difusión. Con la misma idea, lo envié al grupo Buena Señal (ver detalles más abajo).

Un par de observaciones que se me ocurren/puedo hacer sin profundizar demasiado en el tema:

  • Se me ocurren 2 caminos básicos. Samplear algún instrumento en cada frecuencia base requerida y luego asignarlos a las notas adecuadas o generar sonidos sintéticos teniendo en cuenta las mismas frecuencias calculadas.
  • En cuanto a los sonidos sintetizados (generados por computadora) hay que tener también en cuenta los armónicos de cada nota (porque como todos sabrán los instrumentos tienen un timbre particular y no se componen solo de una frecuencia “pura” sino de una frecuencia fundamental y armónicos que son frecuencias múltiplos de la primera con diferentes amplitudes)
  • En cuanto a la parte “física”, por ejemplo se podrían recibir los mensajes convencionales de cualquier teclado MIDI y por medio de este soft específico reproducir las frecuencias adecuadas a la escala elegida.

Como dije antes, también envié la propuesta al grupo Buena Señal, aca les dejo algunas buenas ideas que aportaron:

Por ejemplo, crackerpardo comentó: “Che me gusto la idea, ahora entre la facultad y el trabajo ando algo corto de tiempo como para ayudar bastante pero me parece que podríamos usar ZynAddSubFX, si mal no recuerdo con la síntesis aditiva tenés hasta 64 armónicos con control individual de amplitud y fase por voz, ajustes de tono en ±10 cents (nota: todavia no lei ninguno de los papers adjuntados); también para darle algo mas de realismo se le puede poner un LFO a alguno de los parámetros para hacerlos algo aleatorios o un filtro pasabajo dependiente de la nota para preservar el espectro (eso sería más importante si el sonido fuera sampleado). Bueno, a ver que les parece. Saludos

Por otra parte, Victor Suarez opinó: “Propongo utilizar un teclado común que mande las notas en MIDI, hacer un plugin VST o similar que capture las notas (eventos midi), y que traduzca los eventos de manera que se altere la frecuencia. Lo que habria que hacer es utilizar el comando “pitch bend“, lo que permite “desafinar” la nota en curso. El efecto es el equivalente a estirar una cuerda en una guitarra. Algunos teclados vienen con una ruedita en la esquina superior izquierda para lograrlo. Aca tiene algo sobre el tema de comandos midi, si bien pobremente documentado, pero pueden conseguir mejor info revolviendo la web: MIDI commands

Y Juan Vuletich dijo: “Hola! Yo creo que lo mejor es tomar un vsti open source, como buffersynth2 o Syntopia y agregarles la funcionalidad para elegir la escala, y hacer que usen las frecuencias correctas, no? Suena como algo que se podria hacer en 1 semana. (Si uno tuviera una semana libre, por supuesto!) El proyecto es super interesante. Pero no me animo a ofrecerme como voluntario por falta de tiempo…

Bueno, eso es todo por ahora…
voluntarios? ideas? comentarios? interesados? (pueden dejar un comentario o comunicarse a través del formulario del blog y los pongo en contacto con Luis Enrique Schiller)


, , , , , , , , , ,

Posted in audio, acoustics, signal processing, programming, music theory, instruments, lutheria, projects, math, Castellano, ideas | No Comments »

Calcular una frecuencia a partir de otra según la escala temperada

Posted by hordia on 9th September 2006

La escala temperada, surge como solución para poder tocar en varias tonalidades en un mismo instrumento, sin tener que afinar especialmente cada vez que que se quiere cambiar.
Para ello, entre cada nota se define un intervalo constante llamado semitono, cuyo valor es:

a=2^{\frac{1}{12}}

Cada octava se divide en 12 intervalos (semitonos) cuyas frecuencias se pueden calcular a partir de la primera (que llamaremos F) usando f_{n}=F*a^n=F*2^{\frac{n}{12}}, entonces queda:
 f_0=F, \; f_1=F*a, \; f_2=F*a^2, \; \ldots, \; f_{11}=F*a^{11}, \; f_{12}=F*a^{12} \; = \; 2*F

En este link se puede ver una tabla que compara esta escala con la entonación justa y muestra la diferencia porcentual en frecuencia. También existen escalas que dividen la octava en 19 y 22 partes (ver mas).
Generalmente se asocia con J. S. Bach quien fue uno de los primeros en utilizarla y para demostrar sus posibilidades escribió la obra “El clave bien temperado“.

.

Fórmula para calcular cualquier frecuencia a partir de una frecuencia base en la escala temperada:

frecuencia = 2^{octava}*frecbase*2^{nota/12}

El código equivalente en c sería:
#include "math.h"
float calcular_frec( float octava, float nota ) {
const float frecbase =  27.5; //por ej tomamos como referencia A0=27.5Hz
return pow(2.0f,octava)*frecbase*pow(2.0f,nota/12.0f);
}
Update: Recomiendo leer este post: “La física de la música


, , , , , , , ,

Posted in audio, acoustics, algorithms, music, music theory, c++, math, Castellano | 1 Comment »

 
Cerrar
Enviar por Correo