Apertura del subsistema PCM in modalità Registrazione

Da Gambas-it.org - Wikipedia.

Per aprire il sub-sistema PCM di ALSA in modalità "Registrazione" bisognerà dotarsi di un handle specifico e diverso da quello relativo alla modalità in Riproduzione.

Si utilizzerà come parametro stream, che rappresenta la direzione del flusso dei dati audio, della funzione snd_pcm_open il valore espresso dalla costante di ALSA: SND_PCM_STREAM_CAPTURE.

Pertanto l'apertura del dispositivo PCM di ALSA avverrà in modo simile a quella effettuata la Riproduzione audio.

Si dichiarerà all'inizio la libreria specifica di ALSA:

Library "libasound:2.0.0"

Bisognerà dichiarare e instanziare alcuni valori e tipi di dati come:

  • l'identificativo del dispositivo audio del sistema ALSA, che sarà la seguente stringa:
"default"
  • il valore che identifica la capacità del dispositivo di essere aperto per la intercettazione dei dati audio. Useremo in tal caso una Costante:
Private Const SND_PCM_STREAM_CAPTURE As Byte = 1

ai quali vanno aggiunti il tipo di formato di campionamento ed il tipo di accesso.

La funzione specifica per l'apertura del sub-sistema PCM di ALSA:

int snd_pcm_open(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode)

dovrà essere dichiata con Extern:

Private Extern snd_pcm_open(pcm As Pointer, name As String, _stream As Integer, mode As Integer) As Integer

e potremo, quindi, in subroutine richiamare detta funzione per l'uso:

err = snd_pcm_open(VarPtr(handle), device, SND_PCM_STREAM_CAPTURE, 0)


Impostazioni generali

Le altre impostazioni sono simili alle impostazioni viste per la modalità in Riproduzione.


Funzione per la registrazione dei dati

Useremo la funzione snd_pcm_readi per un accesso di tipo "interleaved" [Nota 1]. Tale funzione legge dall'handle del dispositivo PCM di ALSA un numero di dati, indicato dal suo terzo argomento, e li scrive nella variabile buffer che rappresenta il suo secondo argomento.
Ovviamente tale funzione andrà preventivamente dichiarata con la funzione Extern, e potrà essere così espressa in routine:

snd_pcm_readi(handle, buffer, numframes)

Anche in questo caso bisognerà far sì che l'applicazione chiami la funzione di registrazione prima che il buffer di acquisizione della scheda audio sia completamente riempito. Altrimenti ci sarà un sovraccarico del buffer, e verrà sollevato un corrispondente errore di overrun.


Esempi pratici di registrazione audio

Vediamo di seguito un esempio completo per la registrazione di 13 secondi di dati audio con frequenza di campionamento a 44100 hertz, risoluzione a 16 bit e 2 canali:

Library "libasound:2.0.0"

Private Const SND_PCM_STREAM_CAPTURE As Byte = 1
Private Const SND_PCM_FORMAT_S16_LE As Byte = 2
Private Const SND_PCM_ACCESS_RW_INTERLEAVED As Byte = 3

' int snd_pcm_open(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode)
' Opens a PCM.
Private Extern snd_pcm_open(handleP As Pointer, nome As String, flusso As Integer, mode As Integer) As Integer

' int snd_pcm_hw_params_malloc(snd_pcm_hw_params_t **ptr)
' Allocate an invalid snd_pcm_hw_params_t using standard malloc.
Private Extern snd_pcm_hw_params_malloc(ptr As Pointer) As Integer

' int snd_pcm_hw_params_any(snd_pcm_t *pcm, snd_pcm_hw_params_t *params)
' Fill params with a full configuration space for a PCM.
Private Extern snd_pcm_hw_params_any(pcmP As Pointer, ptrP As Pointer) As Integer

' int snd_pcm_hw_params_set_access(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_access_t _access)
' Restrict a configuration space to contain only one access type.
Private Extern snd_pcm_hw_params_set_access(pcmP As Pointer, ptrP As Pointer, accesso As Integer) As Integer

' int snd_pcm_hw_params_set_format(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, snd_pcm_format_t val)
' Restrict a configuration space to contain only one format.
Private Extern snd_pcm_hw_params_set_format(pcmP As Pointer, ptrP As Pointer, valformat As Integer) As Integer

' int snd_pcm_hw_params_set_channels_first(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val)
' Restrict a configuration space to contain only one channels count.
Private Extern snd_pcm_hw_params_set_channels(pcmP As Pointer, ptrP As Pointer, valP As Pointer) As Integer

' int snd_pcm_hw_params_set_rate_near(snd_pcm_t *pcm, snd_pcm_hw_params_t *params, unsigned int *val, int *dir)
' Restrict a configuration space to have rate nearest to a target.
Private Extern snd_pcm_hw_params_set_rate_near(pcmP As Pointer, ptrP As Pointer, valP As Pointer, dirP As Pointer) As Integer

' int snd_pcm_hw_params_set_period_size_near(snd_pcm_t * pcm, snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val, int * dir)
' Restrict a configuration space to have period size nearest to a target.
Private Extern snd_pcm_hw_params_set_period_size_near(pcmP As Pointer, ptrP As Pointer, valP As Pointer, dirP As Pointer) As Integer

' int snd_pcm_hw_params(snd_pcm_t *pcm, snd_pcm_hw_params_t *params)
' Install one PCM hardware configuration chosen from a configuration space and snd_pcm_prepare it.
Private Extern snd_pcm_hw_params(pcmP As Pointer, ptrP As Pointer) As Integer

' int snd_pcm_hw_params_get_period_size(const snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val, int * dir)
' Extract period size from a configuration space.
Private Extern snd_pcm_hw_params_get_period_size(ptrP As Pointer, valP As Pointer, dirP As Pointer) As Integer

' int snd_pcm_hw_params_get_period_time(const snd_pcm_hw_params_t * params, snd_pcm_uframes_t * val, int * dir)
' Extract period time from a configuration space.
Private Extern snd_pcm_hw_params_get_period_time(ptrP As Pointer, valP As Pointer, dirP As Pointer) As Integer

' snd_pcm_sframes_t snd_pcm_readi (snd_pcm_t *pcm, void *buffer, snd_pcm_uframes_t size)
' Read interleaved frames from a PCM.
Private Extern snd_pcm_readi(pcm As Pointer, buffer As Pointer, size As Long) As Long

' const char * snd_strerror (int errnum)
' Returns the message for an error code.
Private Extern snd_strerror(errnum As Integer) As String

' int snd_pcm_recover (snd_pcm_t *pcm, int err, int silent)
' Recover the stream state from an error or suspend.
Private Extern snd_pcm_recover(pcm As Pointer, err As Integer, silent As Integer) As Integer
    
' snd_pcm_close(snd_pcm_t *pcm)
' Close PCM handle.
Private Extern snd_pcm_close(pcm As Pointer)


Public Sub Main()

 Dim handle, params As Pointer
 Dim device, percorsoTmp As String
 Dim err, fc, dr, cicli As Integer
 Dim buffer As New Short[128]
 Dim dim_buffer, frames As Long
 Dim datigrezzi As File

 device = "default"

' Creiamo il file che ospiterà i dati grezzi audio registrati dall'applicativo:
 percorsoTmp = Temp("filegrezzo")
 datigrezzi = Open percorsoTmp For Create
 datigrezzi.Close

 datigrezzi = Open percorsoTmp For Write Append

''''''''''''''''''''''''''''''''''''''''

' Apre il sub-sistema PCM di ALSA per la registrazione:
 err = snd_pcm_open(VarPtr(handle), device, SND_PCM_STREAM_CAPTURE, 0)
 If err < 0 Then Error.Raise("Errore nell'apertura del sub-sistema PCM: " & snd_strerror(err))

' Alloca un oggetto di parametri hardware:
 snd_pcm_hw_params_malloc(VarPtr(params))

' Imposta valori predefiniti:
 snd_pcm_hw_params_any(handle, params)

' == Imposta i parametri prescelti ==

' Imposta la modalità "Interleaved":
 snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED)

' Imposta il formato di campionamento a 16-bit little-endian:
 snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE)

' Imposta il numero di canali a 2 (stereo):
 snd_pcm_hw_params_set_channels(handle, params, 2)

' Imposta la frequenza di campionamento a 44100 hertz:
 fc = 44100
 snd_pcm_hw_params_set_rate_near(handle, params, VarPtr(fc), VarPtr(dr))

' Imposta la dimensione del periodo a 32 frame:
 frames = 32
 snd_pcm_hw_params_set_period_size_near(handle, params, VarPtr(frames), VarPtr(dr))

' Scrive i parametri nel dispositivo PCM:
 err = snd_pcm_hw_params(handle, params)
 If err < 0 Then Error.Raise("unable to set hw parameters: " & snd_strerror(err))

' Usa un buffer di dimensioni sufficenti per contenere un periodo:
 snd_pcm_hw_params_get_period_size(params, VarPtr(frames), VarPtr(dr))

' Imposta il ciclo per tot secondi:
 snd_pcm_hw_params_get_period_time(params, VarPtr(frames), VarPtr(dr))

 cicli = 400000000 / fc
 dim_buffer = buffer.Count / SizeOf(gb.Short)

 While cicli > 0
' Registra i dati nel buffer:
   frames = snd_pcm_readi(handle, buffer.Data, dim_buffer)
   If frames < 0 Then
     frames = snd_pcm_recover(handle, frames, 0)
     snd_pcm_close(handle)
     Error.Raise("Errore nella registrazione dei dati audio: " & snd_strerror(frames))
   Endif
   If (frames > 0) And (frames < dim_buffer) Then
     snd_pcm_close(handle)
     Error.Raise("Lettura ridotta (atteso: " & CStr(dim_buffer) & ", letto: " & CStr(frames) & ")")
   Endif
' Scrive il file contenente i dati grezzi wav:
   Write #datigrezzi, buffer.Data, buffer.Count * SizeOf(gb.Short)
   Dec cicli
 Wend

' Genera il file WAV finale:
 crea_file(percorsoTmp)

' Va in chiusura:
 datigrezzi.Close
 snd_pcm_close(handle)

End


Private Procedure crea_file(tmp As String)

 Dim dati As String
 Dim i As Integer

' Impostiamo il blocco iniziale generico del file WAV:
 Dim intesta1 As Byte[] = [82, 73, 70, 70]
 Dim intesta2 As Byte[] = [87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 1, 0, 2, 0,
                          &44, &AC, 0, 0, &10, &B1, 2, 0, 4, 0, 16, 0, &64, &61, &74, &61]

 dati = File.Load(tmp)
 i = Len(dati) + 36

' Imposta il valore dimensionale di 4 byte a partire dal 5° byte del futuro file:
 intesta1.Add(i And &FF)
 intesta1.Add(Shr(i And &FF00&, 8))
 intesta1.Add(Shr(i And &FF0000&, 16))
 intesta1.Add(Shr(i And &FF000000&, 24))
 intesta1.Insert(intesta2)
 i = Len(dati)
 intesta1.Add(i And &FF)
 intesta1.Add(Shr(i And &FF00&, 8))
 intesta1.Add(Shr(i And &FF0000&, 16))
 intesta1.Add(Shr(i And &FF000000&, 24))

' Per generare il file WAV finale, eseguibile, uniamo i dati del blocco iniziale ai dati grezzi registrati:
 File.Save("/tmp/FileFINALE.wav", intesta1.ToString(0, intesta1.Count) & dati)

End

Un altro esempio più breve e semplice, come il precedente con frequenza di campionamento a 44100 hertz, risoluzione a 16 bit e 2 canali:

Library "libasound:2.0.0"

Private Const SND_PCM_STREAM_CAPTURE As Byte = 1
Private Const SND_PCM_FORMAT_S16_LE As Byte = 2
Private Const SND_PCM_ACCESS_RW_INTERLEAVED As Byte = 3

' int snd_pcm_open(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode)
' Opens a PCM.
Private Extern snd_pcm_open(handleP As Pointer, nome As String, flusso As Integer, mode As Integer) As Integer

' int snd_pcm_set_params(snd_pcm_t * pcm, snd_pcm_format_t format, snd_pcm_access_t access, unsigned int channels, unsigned int rate, int soft_resample, unsigned Int latency)
' Set the hardware and software parameters in a simple way.
Private Extern snd_pcm_set_params(pcm As Pointer, formatInt As Integer, accesso As Integer, channels As Integer, rate As Integer, soft_resample As Integer, latency As Integer) As Integer

' snd_pcm_sframes_t snd_pcm_readi (snd_pcm_t *pcm, void *buffer, snd_pcm_uframes_t size)
' Read interleaved frames from a PCM.
Private Extern snd_pcm_readi(pcm As Pointer, buffer As Pointer, size As Long) As Long

' const char * snd_strerror (int errnum)
' Returns the message for an error code.
Private Extern snd_strerror(errnum As Integer) As String

' int snd_pcm_recover (snd_pcm_t *pcm, int err, int silent)
' Recover the stream state from an error or suspend.
Private Extern snd_pcm_recover(pcm As Pointer, err As Integer, silent As Integer) As Integer
    
' snd_pcm_close(snd_pcm_t *pcm)
' Close PCM handle.
Private Extern snd_pcm_close(pcm As Pointer)


Public Sub Main()

 Dim handle As Pointer
 Dim device, percorsoTmp As String
 Dim err, fc, cicli As Integer
 Dim buffer As New Short[128]
 Dim dim_buffer, frames As Long
 Dim datigrezzi As File

 device = "default"

' Creiamo il file che ospiterà i dati grezzi audio registrati dall'applicativo:
 percorsoTmp = Temp("filegrezzo")
 datigrezzi = Open percorsoTmp For Create
 datigrezzi.Close

 datigrezzi = Open percorsoTmp For Write Append
 
' Imposta la frequenza di campionamento a 44100 hertz:
 fc = 44100

' Apre il sub-sistema PCM di ALSA per la registrazione:
 err = snd_pcm_open(VarPtr(handle), device, SND_PCM_STREAM_CAPTURE, 0)
 If err < 0 Then Error.Raise("Errore nell'apertura del sub-sistema PCM: " & snd_strerror(err))

' Imposta i parametri del sub-sistema PCM di ALSA per la registrazione:
 err = snd_pcm_set_params(handle, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 2, fc, 1, 0)
 If err < 0 Then Error.Raise("Errore nell'impostazione dei parametri del sub-sistema PCM: " & snd_strerror(err))

 cicli = 400000000 / fc
 dim_buffer = buffer.Count / SizeOf(gb.Short)

 While cicli > 0
' Registra i dati nel buffer:
   frames = snd_pcm_readi(handle, buffer.Data, dim_buffer)
   If frames < 0 Then
     frames = snd_pcm_recover(handle, frames, 0)
     snd_pcm_close(handle)
     Error.Raise("Errore nella registrazione dei dati audio: " & snd_strerror(frames))
   Endif
   If (frames > 0) And (frames < dim_buffer) Then
     snd_pcm_close(handle)
     Error.Raise("Lettura ridotta (atteso: " & CStr(dim_buffer) & ", letto: " & CStr(frames) & ")")
   Endif
' Scrive il file contenente i dati grezzi wav:
   Write #datigrezzi, buffer.Data, buffer.Count * SizeOf(gb.Short)
   Dec cicli
 Wend

 ' Genera il file WAV finale:
 crea_file(percorsoTmp)

' Va in chiusura:
 datigrezzi.Close
 snd_pcm_close(handle)

End


Private Procedure crea_file(tmp As String)

 Dim dati As String
 Dim i As Integer

' Impostiamo il blocco iniziale generico del file WAV:
 Dim intesta1 As Byte[] = [82, 73, 70, 70]
 Dim intesta2 As Byte[] = [87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 1, 0, 2, 0,
                          &44, &AC, 0, 0, &10, &B1, 2, 0, 4, 0, 16, 0, &64, &61, &74, &61]
 
 dati = File.Load(tmp)
 i = Len(dati) + 36

' Imposta il valore dimensionale di 4 byte a partire dal 5° byte del futuro file:
 intesta1.Add(i And &FF)
 intesta1.Add(Shr(i And &FF00&, 8))
 intesta1.Add(Shr(i And &FF0000&, 16))
 intesta1.Add(Shr(i And &FF000000&, 24))
 intesta1.Insert(intesta2)
 i = Len(dati)
 intesta1.Add(i And &FF)
 intesta1.Add(Shr(i And &FF00&, 8))
 intesta1.Add(Shr(i And &FF0000&, 16))
 intesta1.Add(Shr(i And &FF000000&, 24))

' Per generare il file WAV finale, eseguibile, uniamo i dati del blocco iniziale ai dati grezzi registrati:
 File.Save("/tmp/FileFINALE.wav", intesta1.ToString(0, intesta1.Count) & dati)

End

In quest'altro esempio si avrà la possibilità, premendo su un Button posto sul Form, di avviare la registrazione, e premendo su un altro Button di interromperla. Successivamente ripremendo sul primo Button di avviare una nuova registrazione e così via:

Private cicli As Boolean


Library "libasound:2.0.0"

Private Const SND_PCM_STREAM_CAPTURE As Byte = 1
Private Const SND_PCM_FORMAT_S16_LE As Byte = 2
Private Const SND_PCM_ACCESS_RW_INTERLEAVED As Byte = 3

' int snd_pcm_open(snd_pcm_t **pcm, const char *name, snd_pcm_stream_t stream, int mode)
' Opens a PCM.
Private Extern snd_pcm_open(handleP As Pointer, nome As String, flusso As Integer, mode As Integer) As Integer

' int snd_pcm_set_params(snd_pcm_t * pcm, snd_pcm_format_t format, snd_pcm_access_t access, unsigned int channels, unsigned int rate, int soft_resample, unsigned Int latency)
' Set the hardware and software parameters in a simple way.
Private Extern snd_pcm_set_params(pcm As Pointer, formatInt As Integer, accesso As Integer, channels As Integer, rate As Integer, soft_resample As Integer, latency As Integer) As Integer

' snd_pcm_sframes_t snd_pcm_readi (snd_pcm_t *pcm, void *buffer, snd_pcm_uframes_t size)
' Read interleaved frames from a PCM.
Private Extern snd_pcm_readi(pcm As Pointer, buffer As Pointer, size As Long) As Long

' const char * snd_strerror (int errnum)
' Returns the message for an error code.
Private Extern snd_strerror(errnum As Integer) As String

' int snd_pcm_recover (snd_pcm_t *pcm, int err, int silent)
' Recover the stream state from an error or suspend.
Private Extern snd_pcm_recover(pcm As Pointer, err As Integer, silent As Integer) As Integer

' snd_pcm_close(snd_pcm_t *pcm)
' Close PCM handle.
Private Extern snd_pcm_close(pcm As Pointer)


Public Sub Button1_Click()

 Dim handle As Pointer
 Dim device, percorsoTmp As String
 Dim err, canali, fc As Integer
 Dim buffer As New Short[128]
 Dim dim_buffer, frames As Long
 Dim datigrezzi As File

 device = "default"

' Creiamo il file che ospiterà i dati grezzi audio registrati dall'applicativo:
 percorsoTmp = Temp("filegrezzo")
 datigrezzi = Open percorsoTmp For Create

' Imposta la frequenza di campionamento a 44100 hertz:
 fc = 44100

' Imposta il numero di canali:
 canali = 2

' Apre il sub-sistema PCM di ALSA per la registrazione:
 err = snd_pcm_open(VarPtr(handle), device, SND_PCM_STREAM_CAPTURE, 0)
 If err < 0 Then Error.Raise("Errore nell'apertura del sub-sistema PCM: " & snd_strerror(err))

' Imposta i parametri del sub-sistema PCM di ALSA per la registrazione:
 err = snd_pcm_set_params(handle, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, canali, fc, 1, 0)
 If err < 0 Then Error.Raise("Errore nell'impostazione dei parametri del sub-sistema PCM: " & snd_strerror(err))

 cicli = True
 dim_buffer = buffer.Count / SizeOf(gb.Short)

 While cicli   ' Avvia un ciclo infinito per la registrazione
' Registra i dati nel buffer:
   frames = snd_pcm_readi(handle, buffer.Data, dim_buffer)
   If frames < 0 Then
     frames = snd_pcm_recover(handle, frames, 0)
     snd_pcm_close(handle)
     Error.Raise("Errore nella registrazione dei dati audio: " & snd_strerror(frames))
   Endif
   If (frames > 0) And (frames < dim_buffer) Then
     snd_pcm_close(handle)
     Error.Raise("Lettura ridotta (atteso: " & CStr(dim_buffer) & ", letto: " & CStr(frames) & ")")
   Endif
' Scrive il file contenente i dati grezzi wav:
   Write #datigrezzi, buffer.Data, buffer.Count * SizeOf(gb.Short)
' Una brevissima pausa consente all'utente di operare su eventuali oggetti posti sul Form:
   Wait 0.001 
 Wend

 ' Genera il file WAV finale:
 crea_file(percorsoTmp)

' Va in chiusura:
 datigrezzi.Close
 snd_pcm_close(handle)
 Me.Close

End


Public Sub Button2_Click()

 cicli = False

End


Private Procedure crea_file(tmp As String)

 Dim dati As String
 Dim i As Integer

' Impostiamo il blocco iniziale generico del file WAV:
 Dim intesta1 As Byte[] = [82, 73, 70, 70]
 Dim intesta2 As Byte[] = [87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 1, 0, 2, 0,
                          &44, &AC, 0, 0, &10, &B1, 2, 0, 4, 0, 16, 0, &64, &61, &74, &61]

 dati = File.Load(tmp)
 i = Len(dati) + 36

' Imposta il valore dimensionale di 4 byte a partire dal 5° byte del futuro file:
 intesta1.Add(i And &FF)
 intesta1.Add(Shr(i And &FF00&, 8))
 intesta1.Add(Shr(i And &FF0000&, 16))
 intesta1.Add(Shr(i And &FF000000&, 24))
 intesta1.Insert(intesta2)
 i = Len(dati)
 intesta1.Add(i And &FF)
 intesta1.Add(Shr(i And &FF00&, 8))
 intesta1.Add(Shr(i And &FF0000&, 16))
 intesta1.Add(Shr(i And &FF000000&, 24))

' Per generare il file WAV finale, eseguibile, uniamo i dati del blocco iniziale ai dati grezzi registrati:
 File.Save("/tmp/FileFINALE.wav", intesta1.ToString(0, intesta1.Count) & dati)

End


Note

[1] La memorizzazione e la conseguente disposizione dei valori dei campioni in memoria è condizionata dalle opzioni: "Interleaved" e "Non-interleaved". Tale caratteristica viene specificamente e precisamente impostata nel 3° parametro della funzione esterna di ALSA "snd_pcm_set_params( )".
In breve possiamo dire che l'impostazione di quel parametro, e quindi della modalità di registrazione audio, con la costante SND_PCM_ACCESS_RW_INTERLEAVED determina che nel caso di una registrazione "stereo" i dati afferenti ai campioni audio dei due canali saranno memorizzati in memoria in modo alternato uno dopo l'altro , come nel semplice esempio che segue:

| 16-bit 1° canale | 16-bit 2° canale | 16-bit 1° canale | 16-bit 2° canale | e così via......


Scegliendo invece la costante SND_PCM_ACCESS_RW_NONINTERLEAVED, i dati dei campioni audio saranno registrati in blocchi distinti per canali; ossia ad esempio così:

| 16-bit 1° canale | 16-bit 1° canale | 16-bit 1° canale | ...... | 16-bit 2° canale | 16-bit 2° canale | 16-bit 2° canale | .....

Vedere al riguardo anche: