Eseguire un file audio mediante le funzioni esterne del API di GSound

Da Gambas-it.org - Wikipedia.

GSound è una piccola libreria per la riproduzione di suoni, progettata per essere utilizzata tramite GObject Introspection, ed è un wrapper della libreria C libcanberra.

Con la libreria GSound è possibile eseguire file audio di formato "WAV" e "OGG".

E' necessario avere installata nel sistema e richiamare in Gambas la libreria condivisa: "libgsound.so.0.0.2 ".

Mostriamo un semplice esempio, nel quale verrà eseguito un file audio di formato "WAV" con frequenza di campionamento a 44.100 hertz, 16-bit di profondità e 2 canali:

Library "libgsound:0.0.2"

Private Const GSOUND_ATTR_MEDIA_FILENAME As String = "media.filename"

' GSoundContext *gsound_context_new (GCancellable  *cancellable, GError **error)
' Creates and initializes a new GSoundContext.
Private Extern gsound_context_new(cancellable As Pointer, gerror As Pointer) As Pointer

' gboolean gsound_context_set_driver (GSoundContext *context, const char *driver, GError **error)
' Sets the libcanberra driver to driver.
Private Extern gsound_context_set_driver(context As Pointer, driver As String, gerror As Pointer) As Boolean

' gboolean gsound_context_open (GSoundContext *context, GError **error)
' Attempts to open a connection to the backend sound driver.
Private Extern gsound_context_open(context As Pointer, gerror As Pointer) As Boolean

' gboolean gsound_context_play_simple (GSoundContext *context, GCancellable  *cancellable, GError **error, ...)
' The basic "fire-and-forget" play command.
Private Extern gsound_context_play_simple(context As Pointer, cancellable As Pointer, gerror As Pointer, define As String, percorso As String, ptr As Pointer) As Boolean

' void g_object_unref (gpointer object)
' Decreases the reference count of object.
Private Extern g_object_unref(gobject As Pointer)


Public Sub Main()

 Dim ctx As Pointer
 Dim bo As Boolean
 Dim audio As String
 Dim durata, diff As Integer
 Dim tempus As Date
 
  ctx = gsound_context_new(0, 0)
  
' Imposta il driver audio di sistema da utilizzare:
  bo = gsound_context_set_driver(ctx, "alsa", 0)
  If bo = False Then Error.Raise("ERRORE !")
  
  bo = gsound_context_open(ctx, 0)
  If bo = False Then Error.Raise("ERRORE !")
  
  audio = "/percorso/del/file.wav"
  
  bo = gsound_context_play_simple(ctx, 0, 0, GSOUND_ATTR_MEDIA_FILENAME, audio, 0)
  If bo = False Then Error.Raise("ERRORE !")
  
' Assume la durata del file audio wav:
  durata = ((Stat(audio).Size - 44) * 8) / (44100 * 16 * 2) * 1000
  
' Assume l'orario attuale:
  tempus = Time(Now)
  
' Consente la riproduzione del file audio sino al termine della sua durata:
  Do
    diff = DateDiff(tempus, Time(Now), gb.Millisecond)
    Write "\r" & CStr(Time(0, 0, 0, diff))
    Wait 0.001
  Loop Until diff >= durata
  
  Print "\nEsecuzione terminata !"
  
  g_object_unref(ctx)
  
End



Riferimenti