Estrarre da un file MP3 i soli dati audio grezzi mediante la libreria Libmad

Da - Wikipedia.

La libreria Libmad consente di decodificare ad alta qualità con risoluzione di uscita sino a 24-bit i file audio MPEG.

Poiché per l'estrazione dei dati audio grezzi da un file mp3 è necessario l'uso di varie funzioni callback, le inseriremo in un'unica libreria esterna in C, che creeremo appositamente, da richiamare poi nell'applicazione Gambas.

La libreria esterna, che chiameremo ad esempio mad.c, contenente le funzioni callback del API di Libmad sarà la seguente:

* libmad - MPEG audio decoder library
* Copyright (C) 2000-2004 Underbit Technologies, Inc.
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
* $Id: minimad.c,v 1.4 2004/01/23 09:41:32 rob Exp $

# include <stdio.h>
# include "mad.h"

* This is perhaps the simplest example use of the MAD high-level API.
* Standard input is mapped into memory via mmap(), then the high-level API
* is invoked with three callbacks: input, output, and error. The output
* callback converts MAD's high-resolution PCM samples to 16 bits, then
* writes them to standard output in little-endian, stereo-interleaved
* format.

int decodifica(unsigned char const *, unsigned long, const char *);
static enum mad_flow input(void *, struct mad_stream *);
static enum mad_flow output(void *, struct mad_header const *, struct mad_pcm *);
static enum mad_flow error(void *, struct mad_stream *, struct mad_frame *);

FILE *fl;

* This is a private message structure. A generic pointer to this structure
* is passed to each of the callback functions. Put here any data you need
* to access from within the callbacks.
struct buffer {
  unsigned char const *start;
  unsigned long length;

* This is the function called by main() above to perform all the decoding.
* It instantiates a decoder object and configures it with the input,
* output, and error callback functions above. A single call to
* mad_decoder_run() continues until a callback function returns
* MAD_FLOW_STOP (to stop decoding) or MAD_FLOW_BREAK (to stop decoding and
* signal an error).
int decodifica(unsigned char const *start, unsigned long length, const char * percorso)
  struct buffer buffer;
  struct mad_decoder decoder;
  int result;

 fl = fopen(percorso, "w");

/* initialize our private message structure */

 buffer.start  = start;
 buffer.length = length;

 /* configure input, output, and error functions */

  mad_decoder_init(&decoder, &buffer,
      input, 0 /* header */, 0 /* filter */, output,
      error, 0 /* message */);

 /* start decoding */

 result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);

 /* release the decoder */

  return result;

* This is the input callback. The purpose of this callback is to (re)fill
* the stream buffer which is to be decoded. In this example, an entire file
* has been mapped into memory, so we just call mad_stream_buffer() with the
* address and length of the mapping. When this callback is called a second
* time, we are finished decoding.

static enum mad_flow input(void *data,
       struct mad_stream *stream)
  struct buffer *buffer = data;

  if (!buffer->length)
    return MAD_FLOW_STOP;

  mad_stream_buffer(stream, buffer->start, buffer->length);

  buffer->length = 0;


* The following utility routine performs simple rounding, clipping, and
* scaling of MAD's high-resolution samples down to 16 bits. It does not
* perform any dithering or noise shaping, which would be recommended to
* obtain any exceptional audio quality. It is therefore not recommended to
* use this routine if high-quality output is desired.

static inline
signed int scale(mad_fixed_t sample)
 /* round */
  sample += (1L << (MAD_F_FRACBITS - 16));

 /* clip */
  if (sample >= MAD_F_ONE)
    sample = MAD_F_ONE - 1;
  else if (sample < -MAD_F_ONE)
    sample = -MAD_F_ONE;

 FONT color=gray>/* quantize */</font>
  return sample >> (MAD_F_FRACBITS + 1 - 16);

* This is the output callback function. It is called after each frame of
* MPEG audio data has been completely decoded. The purpose of this callback
* is to output (or play) the decoded PCM audio.

static enum mad_flow output(void *data,
        struct mad_header const *header,
        struct mad_pcm *pcm)
  unsigned int nchannels, nsamples;
  mad_fixed_t const *left_ch, *right_ch;

 /* pcm->samplerate contains the sampling frequency */

  nchannels = pcm->channels;
  nsamples  = pcm->length;
  left_ch   = pcm->samples[0];
  right_ch  = pcm->samples[1];

  while (nsamples--) {
    signed int sample;

   /* output sample(s) in 16-bit signed little-endian PCM */

    sample = scale(*left_ch++);
    fputc((sample >> 0) & 0xff, fl);
    fputc((sample >> 8) & 0xff, fl);

    if (nchannels == 2) {
      sample = scale(*right_ch++);
      fputc((sample >> 0) & 0xff, fl);
      fputc((sample >> 8) & 0xff, fl);


* This is the error callback function. It is called whenever a decoding
* error occurs. The error is indicated by stream->error; the list of
* possible MAD_ERROR_* errors can be found in the mad.h (or stream.h)
* header file.

staticnum mad_flow error(void *data,
       struct mad_stream *stream,
       struct mad_frame *frame)
  struct buffer *buffer = data;

    fprintf(stderr, "decoding error 0x%04x (%s) at byte offset %lu\n",
    stream->error, mad_stream_errorstr(stream),
    stream->this_frame - buffer->start);

 /* return MAD_FLOW_BREAK here to stop decoding (and propagate an error) */


Avremo cura di porre questo codice C della libreria esterna nella cartella Dati del nostro applicativo Gambas.

La parte dell'applicazione con il codice Gambas, invece, sarà la seguente:

Library "libc:6"

Private Const PROT_READ As Integer = 1
Private Const MAP_SHARED As Integer = 1
Private Const MAP_FAILED As Integer = -1

' void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
' Creates a new mapping in the virtual address space of the calling process.
Private Extern mmap(addr As Pointer, length As Integer, prot As Integer, flags As Integer, fd As Integer, offset As Integer) As Pointer

' Dichiariamo la libreria esterna ad hoc contenente le funzioni di Libmad:
Private Extern decodifica(p As Pointer, l As Long, s As String) As Integer In "/tmp/mad"

Public Sub Main()

 Dim percorsoFile, file_ricostruito As String
 Dim st_size As Long
 Dim fl As File
 Dim fdm As Pointer
 Dim bh As Byte[] = [&52, &49, &46, &46, &00, &00, &00, &00, &57, &41, &56, &45, &66, &6D, &74, &20, &10, &00, &00, &00, &01, &00, &02, &00,
                     &44, &AC, &00, &00, &10, &B1, &02, &00, &04, &00, &10, &00, &64, &61, &74, &61, &00, &00, &00, &00]   ' Blocco d'intestazione del file wav futuro: 2 canali, 16 bit, hz 44100

' Generiamo la libreria esterna condivisa contenente le funzioni di Libmad:
   Shell "gcc -o /tmp/ " & Application.Path &/ "/mad.c -shared -lmad -fPIC" Wait
   percorsoFile = "/percorso/del/file.mp3"
   file_ricostruito = "/tmp/dati_grezzi"
   st_size = Stat(percorsoFile).Size
   fl = Open percorsoFile For Read

   fdm = mmap(0, st_size, PROT_READ, MAP_SHARED, fl.Handle, 0)
   If fdm = MAP_FAILED Then Error.Raise("Errore alla funzione 'mmap()' !")

   decodifica(fdm, st_size, file_ricostruito)
' Per riscontro, costituiamo il corrispondente file wav con i dati grezzi prelevati:
   File.Save("/tmp/file_ricostruito.wav", bh.ToString(0, bh.count) & File.Load("/tmp/dati_grezzi"))

' Va in chiusura:
   Print "\nProcedura terminata !"


[1] Madlld

[2] MPEG Audio Decoder