Recently I been playing with python bindings for the CLAM library. Here is a demo demonstrating how to interactively build a network and play a file using the IPython shell:
Related scripts: playfile.py fft_example.py
Recently I been playing with python bindings for the CLAM library. Here is a demo demonstrating how to interactively build a network and play a file using the IPython shell:
Related scripts: playfile.py fft_example.py
This script is about a basic code generation of a CLAM plugin. In some point I think this is some kind of meta-programming or perhaps the term “automatic programming” fits better. The basic idea is to specify some basic features of the planned new processing in a plain text and then, generate some code with the script, saving in this way many of the often repetitive and mechanical work needed to set-up a new processing from scratch. Main intention is to allow concentrate in the Do() function or plugin details quickly.
As an example, I will reproduce here how I worked with me some time ago:
One day, in the irc #clam channel:
“[11:51] <groton> Consul, do you know if there is any trigger-like processing unit, list when the volume gets louder than a threshold or something like that”
I’m not Consul in the irc (I’m hordia), but next day at my console…
cd CLAM/scripts/TemplatedPluginsGenerator
vi ThresholdTrigger.template
Name:ThresholdTriggerTemplate
BaseClass:Processing
i:AudioInPort,Audio Input
ic:0,1,Threshold
oc:0,1,Trigger
In words, this means a Processing template named “ThresholdTriggerTemplate” using “Processing” as a base class and with one input of “AudioInPort” type named “Audio Input”, with one in control in the 0..1 range named “Threshold” and one out control named “Trigger”. Of course, you can add as many inputs/outputs of ports or controls as you want.
This script creates the template:
./TemplateGenerator.py ThresholdTrigger.template
And this one the processing plugin:
./TemplatedPluginsGenerator.py ThresholdTrigger ThresholdTriggerTemplate "Hernán Ordiales" GPL 2008
Again in words, this means create a new processing called “ThresholdTrigger” based on the “ThresholdTriggerTemplate” filling the copyright with my name plus the current year and the license with the GPL text.
A final edit just typing the required code for the Do() function:
cd CLAM/plugins/ThresholdTrigger vi ThresholdTrigger.hxx
#include <cmath>
bool Do()
{
bool result = Do( mAudioInput.GetAudio() );
mAudioInput.Consume();
return result;
}
bool Do(const Audio& in)
{
int size = in.GetSize();
const DataArray& inb = in.GetBuffer();
TData threshold = mThreshold.GetLastValue();
bool trigger = 0;
for (int i=0;i<size ;i++)
{
if (std::fabs(inb[i])>threshold)
trigger = 1;
}
mTrigger.SendControl(trigger);
return true;
}
</size></cmath>
At this point, just remains add the basic SConstruct file for a CLAM plugin, compile it with the corresponding clam_prefix and install it:
scons install clam_prefix=$CLAM_PATH
NetworkEditor
And ready to use…
This example it’s very simple and has a poor implementation but was just to show the idea of how those scripts can save a lot of work.
Update: I made a frontend for these scripts: ProcessingCodeGenerator
Este post surge dado que recientemente redescubrí la radio de last.fm. Principalmente gracias a que me bajé el programa que proveen ellos (btw, multiplaforma y Software Libre). Digo que redescubrí porque antes la usaba desde el amarok, cosa que esta bien, ya que uno centraliza todo ahi, pero este programita tiene algunas cosas piolas y en algunas situaciones es mucho más cómodo de usar, sobre todo para cambiar de radios, por artistas o tags, etc y encima te tira algo de data (parecido a lo que tiene el amarok que busca en wikipedia, nada más que “propiedad” de last.fm). Pero lo que me hizo “engancharme” es el tema de poner un artista que me guste y que me empiece a tirar temas con la misma onda, cosa que me hace conocer canciones e interpretes nuevos. ¿Por qué cuento esto? Por que desencadeno en que comience a usar seguido el botón de “Love”/”Favorito” de la aplicación, que es una forma de decirle a last.fm que ese tema te gusta y que lo tenga en cuenta para volverlo a pasar en el futuro o para (supongo) que tengan más probabilidad de aparecer temas similares (si no te gusta para nada, también se puede “bannear”). Bueno, todo esto viene dado que de tanto presionar “love” (y descubrir/redescubrir varios artistas, sobre todo en blues y jazz) queria tener una forma de acceder a todo eso (nombre del tema + interprete). El programa en cuestión muestra una lista de las canciones recientemente maracadas como favoritas, pero no permite copy&paste y tampoco vía web hay forma de acceder a esa información, como si pasa con otras cosas, por ejemplo las canciones recientemente escuchadas… (con la nueva versión del sitio si se puede: Last.fm: The Next Generation)
Bueno, buscando un poco di con la API (versión 2.0), al parecer reciente, pero sin la capacidad de “recuperar” las últimas loved songs… asi que me remití a la versión 1.0 que si lo permite y además se puede usar sin api key. Entonces lo que hice fue armarme un script en python que descargara las últimas canciones “favoritas” y las vaya guardando en un xml (o .txt), es decir a medida que aparecen nuevas, las agrega y elimina los duplicados…
El script es este: recentLovedTracksList.py
Tip: si uno quiere estar seguro de no perderse ninguna canción, dado que las “canciones favoritas recientes” son solo 10, puede poner este script a correr en cron… (si es que va marcar muchas canciones como favoritas, pero a lo sumo y con mucha suerte uno marca como “loved” una por hora y la frecuencia por supuesto tiende bajar)
Ya que estaba jugando con la api, hice otro script para descargarme todo el historial de escucha (otra “feature” que no vi disponible vía web, pero por suerte con un poco de “hacking” se puede hacer con la API):
No se para que me puede servir, pero es info mía y ya que la tiene otra persona, al menos me gusta poder tenerla yo
Ya que escribo sobre last.fm aprovecho para comentar un par de “nuevos usos” que se me ocurrieron de este tipo de sistemas, ambos se aplican a un player haciendo scrobbling en una fiesta/reunión:
Hace bastante tiempo que tenia archivada esta conversación sobre síntesis por FM y Horgand que quería publicar.
Qué es Horgand? un sintetizador por soft capaz de realizar sonidos de órgano y otros tipos de sonido como pianos eléctricos (Rhodes , Wurlitzer, DX E.Piano ), Jazz Guitar, Strings, Brass, Fretless Bass, Accordion etc. Esta basado en síntesis por FM, según su web:
“Is based on a FM audio synthesizer with twenty carriers (20) without modulators in a plain based algorithm.
each carrier frequency can be modified for construct complex sounds. The synthesizer incorporate also a LFO (Low frequency oscillator) for generate tremolo effects and detune effects applying LFO Pitch and Amplitude to the carrier frequency’s. Some synthesizer parameters can be edited for each sound including two ADSR, (Normal and Percussion), Fine Frequency, Attenuation, Rotary Amplitude, Transpose, etc. Four DSP effects are available for obtain more complex sounds, Rotary, Chorus, Delay and Reverberation. Sounds are stored in banks of 32 organ sounds and can be changed externally with MIDI program change (1-32).”
También incorpora reconocimiento de acordes para producir acompañamiento automático (bajo y bateria) y con líneas de bajo editables para cada ritmo.
Ejemplo de como suena: Horgand_demo.ogg
No conozco mucho de síntesis por FM y tenía curiosidad de como lograba el sonido y terminó saliendo una especie de entrevista improvisada, creo que puede ser interesante para quienes quieran adentrarse en este tipo de programación.
La conversación:
—
<hordia> despues me tenes que contar en que te basaste para conseguir el sonido de horgand digitalmente…
<holborn> pues en el DX7 …. tiene 32 algoritmos de colocacion de los operadores … pero si usas el plano (todos en linea)… todo lo que hagas suena a organo … a partir de ahi … pues añadirle los efectos … y claro en vez de 6 “osciladores” hay 10 … que en realidad son 20 … con lo cual pues es mas rico que un emulador de dx7 tipo hexter o en el dx7 mismo … en realidad .. para usar 20 osciladores no chupa CPU nada … otros porgramas usan 3 y ch
<holborn> claro que para ahorrar cpu .. tuve que limitar algunos parametros de edicion … pero bueno … yo lo que queria era que sonara … si nadie se pone a editar sonidos … ni dios vaya …
<hordia> que es el DX7?
me suena a un teclado legendario pero no estoy seguro…
<holborn> el DX7 fue el primer sintetizador FM … es de yamaha .. y fue una revolucion porque era el primero que mas o menos imitaba bien sonidos reales … algunos mejor que otros …
<holborn> los vendieron todos y mas …
<holborn> yo realmente era un experto … en aquella epoca ni dios sabia nada de musica electronica … yo me hice un curso que daba un loco de la musica electronica .. y sabia programar sintes cosa que nadie sabia .. te estoy hablando de hace mil años …
<holborn> cuando salio el DX7 pues me tuve que empapar toda la info porque realmente es muy diferente a un sinte analogico tradicional … y bueno .. le pedi a un amigo que trabajaba en un distribuidor de yamaha .. que me consiguiera info de verdad … de hecho todavia la conservo ..por ahi ..
<hordia> :O
<holborn> yo llegue a trabajar programando sintes en un estudio de grabacion …. vaya no todos los dias pero me llamaban de vez en cuando
<holborn> haciendo presets … me refiero .. claro
<hordia> veo que horgand es el resultado de muchos años de experiencia…
<holborn> si … a ese nivel si … pero todo fue gracias a un ejemplo de la web de alsa .. .se llama fmminisynth.c … o lago asi … 100 lineas de codigo … entonces se me ocurrio … y empece ..
<holborn> luego buscando … encuentras mil ejemplos de codigo … en HArmony Central … no esta el codigo pero explican como funcionan los efectos … en cristiano .. sin mucha matematica … esta muy bien .. luego ya el implementarlo es cosa de uno … pero el mismo Paul Nasca dice por ahi (el del zyn) que se basa en esa explicaciones … y yo tambien claro ![]()
<holborn> ya te aseguro que su implementacion es mejor que la mia ![]()
<hordia> jeje
<holborn> ahora …la mia consume un tercio de cpu que la suya ![]()
<hordia> entonces hay que ver que parametros se toman para definir cual es mejor ![]()
<holborn> pues es un sinte … lo que suena … sus efectos suenan mejor …. pero … el usa 3 o 4 osciladores por sonido … yo uso 20 … con lo cual en algun lado hay que recortar …
—
El ejemplo que se menciona: miniFMsynth.c
Hace un tiempo, cuando le regalé a mi hermana un afinador para violín, para mi sorpresa (por que lo ignoraba) me enteré que hasta los afinadores más baratos incorporan el afinado por vibración (de la madera). Esto es muy conveniente por que elimina ruidos externos de una manera natural, algo imagino casi imprescindible para un violín tradicional (sin micrófonos) que en general se afina en presencia de otros instrumentos de una orquesta. Lo que se hace es colocarlo en alguna parte del instrumento con una especie de prensa que tiene para que quede bien sujeto. La verdad que me gustó.
(el afinador era un: matrix gt2)
After prototype different kind of simple distortions in NetworkEditor i managed to port all them to ladspa plugins. Despite the fact that the task was less difficult than i had expected at first, prototype with CLAM first worth a lot. Probably, if i had begun coding directly to ladspa source, reach the same status would be taken to me 10 or more times more. I think also was very interesting as “development process”, instead of modeling for example with matlab, you could easy modeling (among other things) in CLAM, and then, if you want/need make your final product by your own.
More, the other day i learned that is already possible to compile ladspa plugins directly from CLAM networks… very cool! Though i think this feature is not completely ready yet and i’m still have to dig in it, i don’t think that i have lost time porting manually because now i have a better knowledge and understanding about ladspa specification that for sure will be useful to work with this (for me “new”) feature, that probably needs some fixes.
About the ladspa plugins programming, i just downloaded the sdk from ladspa.org, read some of the ladspa.h file and some basic examples (the ones from sdk) and that was enough to handle the basis. Ah, i had to ask for some ladspa ID’s for my plugins here: ladspa at muse.demon.co.uk
On the other hand i’ve forwarded my distortion examples to musix distro folks and some of them indeed have tried it and made a couple of jack-rack presets and audio demos. More info about this here: DSP-es#Presets, ogg demos and jack-rack presets, and patchs review.
Next step (in my TODO list): produce ladspa binaries directly from CLAM networks.
I have uploaded these plugins here: disthordian ladspa plugins.
A week or more ago, Daniel Vidal Chornet (collaborator of Musix) asked me if i can develop guitar distortion effects, because he couldn’t find something decent that suits his needs, i said “sadly i have no idea about distortions effects and anyway i have no time right now to do that”, but then i remembered how useful could be the clam framework and i tried to do a little spike about. Results were better than i had expected at first (is not a super cool distortion, but at least sound like one).
Basically i merged and tweaked a couple of simple/base algorithms found in the web for distortion and compression and in less than 30 minutes i had something working and sounds like a guitar distortion (”clean” ones seems to sound better easily). I was amazed how fast and easy (develop and test in clam/networkeditor, once you get the basis) was. I think right now is far to be a good distortion, but as learning process and first demo seems very good.
Here some sound examples:
Original: Download audio file (dvlc-guitar.mp3)
(dvlc-guitar.ogg)
With distortion: Download audio file (guitardist-ex1.mp3)
(guitardist-ex1.ogg)
Test network looks like:

The source code is here (as NetworkEditor plugin): GuitarDistortion.tar.gz
Some optional tweaks could include add a three band filter but i’m still not sure if it’s better to put it at first or at the end.
Special thanks for testing and audio samples to Daniel Vidal Chornet. I should take from my closet my fender stratocaster and do my own samples
. OTOH, we already arrange to do a remote gig with this.
Another useful NetworkEditor processings plugins i had made during this “work”:
Related: LADSPA versions of my recent simple distortions
Update: Distortion rack prototype
/usr/share/qt3/bin/moc ./plugin_kateopenheader.h -o plugin_kateopenheader.moc
make
sudo libtool --mode=install install -c kateopenheaderplugin.la /usr/lib/kde3/kateopenheaderplugin.la
kbuildsycoca
QStringList headers( QStringList() << "h" << "H" << "hh" << "hpp" << "hxx" );instead of
QStringList headers( QStringList() << "h" << "H" << "hh" << "hpp" );
Hoy vi el video demostración de TAPESTREA: Techniques And Paradigms for Expressive Synthesis, Transformation, and Rendering of Environmental Audio (también conocido como taps). Intenta ser un entorno para el diseño de sonido, pero desde un enfoque totalmente nuevo (lo mejor es ver el video para entender mejor de que se trata).
Me llamó la antención (además de la división del sonido entre sus componentes sinusoidales, transitorios y residuo), la interfaz gráfica intuitiva y sencilla y la manipulacíón de sonidos en el espectrograma.
TAPESTREA: Sound Scene Modeling By Example - For more funny movies, click here
El video completo esta disponible aca: http://soundlab.cs.princeton.edu/listen/taps/tapestrea.mov
Según su web, la idea es ser un framework unificado para analizar de forma interactiva sonidos complejos, transformarlos y sintetizarlos:
TAPESTREA otorga una nueva forma de transformar dinámicamente una escena de sonido, permite generar puestas de cualquier duración, facilita la composición y el diseño de sonido combinando elementos de diferentes grabaciones de forma muy sencilla y ofreciendo miles de variantes para su manipulación (solo pensar en las posiblidades que otorga el solo hecho de poder manejar por separado sinusoides, transitorio y residuo).
Sin duda, una herramienta de trabajo interesante tanto para “diseñadores de sonido” como invesitigadores del audio, compositores y cualquier persona interesada en experimentar con el sonido.
Por si todo esto fuera poco, es Software Libre y multiplataforma. El código fuente y los binarios se consiguen aquí.
Más info:
Yesterday I had the opportunity to give a talk about my recent work in the google summer of code at the VI Jornadas de Acústica, Electroacústica y áreas vinculadas (CADAE). The given time was short, so was a little hard to explain all in only 20 minutes, but seems that all went well (at least seemed like the people). Here my presentation (in Spanish):
Download: Transformaciones espectrales en tiempo real para CLAM.pdf
Ayer tuve la oportunidad de presentar mi trabajo realizado para el google summer of code en el marco de las VI Jornadas de Acústica, Electroacústica y áreas vinculadas (CADAE), les dejó la presentación de la misma:
Download: Transformaciones espectrales en tiempo real para CLAM.pdf
Me llega vía mail/boletín de IEEE Argentina que el próximo lunes 3 de septiembre se va a dar la conferencia ‘Tackling the Acoustic Front-end for Distant-Talking Automatic Speech‘ dictada por el Prof. Dr.-Ing. Walter Kellerman, conferencista distinguido de la IEEE Signal Processing Society. Esto será en la Sede de IEEE / CICOMRA, con entrada libre y gratuita.
With the ever-growing interest in ‘natural’ hands-free acoustic human/machine interfaces, the need for according distant-talking automatic speech recognition (ASR) systems increases. Considering interactive TV as a challenging exemplary application scenario, we investigate the structural problems presented by noisy and reverberant multi-source environments with unpredictable interference and acoustic echoes of loudspeaker signals, and discuss current acoustic signal processing techniques to enhance the input to the actual ASR system. Special attention is paid to reverberation, which affects speech recognizers much more than human listeners, and a recently published method incorporating a reverberation model on the feature level of ASR is discussed.
Walter Kellermann is Professor for communications at the Chair of Multimedia Communications and Signal Processing of the University of
Erlangen-Nuremberg, Germany. His current research interests include speech signal processing, array signal processing, adaptive filtering, and its applications to acoustic human/machine interfaces. He received the Dipl.-Ing. (univ.) degree in Electrical Engineering from the University of Erlangen-Nuremberg in 1983, and the Dr.-Ing. degree (’with distinction’) from the Technical University Darmstadt, Germany, in 1988. From 1989 to 1990, he was a Postdoctoral Member of Technical Staff at AT&T Bell Laboratories, Murray Hill, NJ. In 1990, he joined Philips Kommunikations Industrie, Nuremberg, Germany. From 1993 to 1999 he was a professor at the Fachhochschule Regensburg before he joined the University Erlangen-Nuremberg as a professor and head of the audio research laboratory in 1999 (for more see http://www.LNT.de/audio). In 1999 he co-founded the consulting firm DSP Solutions. Dr. Kellermann authored or co-authored eight book chapters and more than 100 refereed papers in journals and conference proceedings. He served as a guest editor to various journals, as an associate editor and guest editor to IEEE Transactions on Speech and Audio Processing from 2000 to 2004, and presently serves as associate editor to the EURASIP Journals on Signal Processing and on Advances in Signal Processing. He was the general chair of the 5th International Workshop on Microphone Arrays in 2003 and the IEEE Workshop on Applications of Signal Processing to Audio and Acoustics in 2005. For 2007 and 2008 he is a Distinguished Lecturer of the IEEE Signal Processing Society.
Fecha y hora: Lunes 3 de setiembre a las 19:00
Lugar: Auditorio IEEE/CICOMRA, Av. Córdoba 744 Piso 1 B, Buenos Aires
Inscripción: No es arancelada, pero se solicita inscripción previa vía web completando el formulario disponible aca. Alternativamente por e-mail a sec.argentina@ieee.org citando ‘Conferencia SPS-01‘ o por teléfono a IEEE / CICOMRA (011) 4325 8839.
No hay charlas ni mucho movimiento sobre este tipo de cosas por aca, asi que voy a tratar de ir… y después, de hacerme tiempo para un review de la misma.
De casualidad (buscando otra cosa) me topé con esto: Audio Player Wordpress plugin. Parece bastante bien logrado y lo instalé en este blog… (además en este último tiempo venia averiguando sobre estos temas, ver: “Streaming audio from your website (mp3 and ogg!)” y “Many files to stream with cortado in the same page“). Al estar basado en flash, solo soporta mp3, pero es bastante configurable y tiene cosas copadas como la posibilidad de agregar audios por defecto al inicio o al final de cada track (útil por ejemplo para anuncios comerciales en podcasts o instrucciones de uso), distintas alternativas de mostrado de los audios en el feed, configuración de colores y otras cosas más.
También se puede usar en sitios no basados en wordpress (ver tutorial) y por ejemplo es el que usa digg.com para los podcasts (ver).
Ejemplo:
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 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:
It’s easy to arrive at this:
and then, also taking in account this mathematical relation::
the final formula looks like:
and a final c++ code like:
fund_midinote = round( 69. + log(fundfrec/440.)*17.31234 );
Andrés Kasulin, a friend of mine from the University gave me some light about the issue of SMS interference (check “Catching (phone) SMS pulse train with CLAM…“)
He says in a comment from that post:
“I’ve found nice data in wikipedia[1].
It seems to be radiofrequency interference produced by the the phone, and filtered by the mic-cable-probes-osciloscope system. I think there is only a square pulse because the carrier frequency is much higher than filter cutoff frequency (maybe near 10^5 times).”
[1] http://en.wikipedia.org/wiki/GSM#Radio_interface
I’d add from that article:
“A nearby GSM handset is usually the source of the “dit dit dit, dit dit dit, dit dit dit” signal that can be heard from time to time on home stereo systems, televisions, computers, and personal music devices. When these audio devices are in the near field of the GSM handset, the radio signal is strong enough that the solid state amplifiers in the audio chain function as a detector. The clicking noise itself represents the power bursts that carry the TDMA signal. These signals have been known to interfere with other electronic devices, such as car stereos and portable audio players. This is a form of RFI, and could be mitigated or eliminated by use of additional shielding and/or bypass capacitors in these audio devices. However, the increased cost of doing so is difficult for a designer to justify.”
Very thanks Andrés!
Hace un tiempo escribí un par de funciones para trabajar con wavs en python como si fuesen vectores, es decir, al “estilo” matlab (para más detalles ver este post “Funciones para trabajar con wav’s vectorialmente en python“).
Casualmente en la misma semana 2 personas, Cesar Perez (Colombia) y Elizabeth Coixet (España), me escribieron a este blog comentandome que estaban usando mis funciones con éxito pero tenian problemas al leer wav’s de 8 bits. Les recomendé que lo charlaramos en el grupo Buena Señal ya que entre todos (y posiblemente alguna contribución de alguno más de los del grupo) seguramente iba a ser más fácil y todos podriamos aprender algo de ello (ver estos 2 threads: 1, 2).
Y asi fue
Luego de que Cesar planteara el problema y yo hiciese mis apreciaciones sobre el asunto, Elizabeth encontró que el wav de 8 bits era unsigned y no signed (como el de 16 bits) con lo que se termino de resolver el misterio de porque la solución que manejabamos leia en forma extraña…
Bueno la función queda asi:
# Example: [ y, Fs, bits ] = wavread8bits( 'filename' )
def wavread8bits( name ):
file = wave.open( name, 'r' )
[Channels,Bytes,Fs,Frames,Compress,CompressName] = file.getparams() # (nchannels, sampwidth in bytes, sampling frequency, nframes, comptype, compname)
Bits = Bytes*8 # 8 bits per sample
Data = file.readframes( Frames )
Data = (fromstring( Data, UInt8 ) / 128.0 ) - 1.0 # -1..1 values
print "Fs: ",Fs,"\nBits: ",Bits,"\nChannels: ",Channels
file.close()
return Data, Fs, Bits
De paso también escribí la función para escribir un wav de 8 bits.
# Example: wavwrite8bits( y, Fs, filename )
def wavwrite8bits( data_array, Fs, name ):
file = wave.open( name, 'w' )
file.setframerate( Fs ) # sets sampling frequency
file.setnchannels( 1 ) # sets number of channels
file.setsampwidth( 1 ) # number of bytes, 8 bits per sample
clipped = False
block_size = 1024*10 # write block size: 10k
a_max = 255 # max amp
a_min = 0 # min amp
n = 0
len_data_array = len( data_array ) # 1 byte (UInt8) data
while n < len_data_array :
frame = '' # string frame of 'block_size'
for i in range( block_size ) :
if n < len_data_array :
newbyte = int( (data_array[n]+1.0) * 128 ) # ~ 255/2
if newbyte > a_max or newbyte < a_min : clipped = True
newbyte = min( max(newbyte,a_min), a_max ) # normalization, 0..255
#newbyte.clip( min=a_min, max=a_max ) # normalization, 0..255
frame += chr( newbyte & 0xFF ) # takes the byte, converts it to char and adds it to the frame
n += 1
file.writeframes( frame )
if clipped == True : print "Warning: Some values were clipped"
print "Final length:", len_data_array/512,"kb" # n*2/1024 (bytes size/1024) = n/512
file.close()
El archivo con todas estas funciones de lectura/escritura (8 y 16 bits) es este: wav_array.py
Gracias a todos!