Tutorial: playing firing sound
==============================

Playing a firing sound as long as left CTRL is pressed,
using vg_sound_pate() and vg_sound_catb().


step 1
At first we have to initialize VgaGames
and open a window or switch to graphical screen.

==>
int main(int argc, char ** argv) {
  char * arg0;  // for the name of the program
  char buf[64];  // for explaining text
  int fire_status;

  /* initialize vgagames, always pass argv[0] */
  if (vg_init_vgagames(argv[0],0,NULL) < 0) {exit(1);}

  /* open window */
  if ((arg0=strrchr(argv[0],'/'))==NULL) {arg0=argv[0];} else {arg0++;}
  if (vg_window_open(arg0,0,0) < 0) {exit(1);}
<== step 2 Start soundserver, load the sound file and draw an explaining text. ==>
  /* start soundserver */
  if (vg_sound_startserver(0,0,NULL) < 0) {vg_window_close(); exit(1);}

  /* load firing-sound-file attaching it to nickname "s-fire" */
  vg_sound_attach("sound/shot.wav","s-fire",100);

  /* draw explaining text */
  snprintf(buf,sizeof(buf),"Fire: left [CTRL], End: Space");
  vg_bitmap_clear(NULL,RGB_BLACK);
  vg_draw_text(NULL,RGB_WHITE,(SC_WIDTH-strlen(buf)*vg_font_width(NULL))/2,(SC_HEIGHT-vg_font_height(NULL))/2,buf,NULL,RGB_FULL);
  vg_window_flush();
<== step 3 Program loop: play sound in an endless loop, using vg_sound_pate() if left [CTRL] is released, using vg_sound_catb() if left [CTRL] is pressed again. ==>
  /* program loop */
  fire_status=0;  /* sound still not started */
  for (;;) {
    /* update key and mouse events */
    vg_key_update();

    /* end loop if SPACE pressed */
    if (vg_key_pressed(KEY_SPACE, SHORTKEY)) {break;}

    /* left CTRL pressed: play firing sound */
    if (vg_key_pressed(KEY_LCTRL, LONGKEY)) {
      if (fire_status==0) {  // start sound in an endless loop
        vg_sound_play("s-fire",0,0);
      } else if (fire_status==2) {  // sound is paused at end
        vg_sound_catb("s-fire");
      }
      fire_status=1;  // sound now playing
    } else {  // left CTRL not pressed
      /* if sound is playing, don't stop it immediately but at its end */
      if (fire_status==1) {  // sound is playing
        vg_sound_pate("s-fire");
        fire_status=2;  // sound now paused at end
      }
    }
  }
  /* stop sound if running */
  if (fire_status > 0) {vg_sound_stop("s-fire",0);}
<== step 4 Do the rest. ==>
  /* end soundserver and close window */
  vg_sound_endserver();
  vg_window_close();

  exit(0);
}
<== Alternative To get an idea what is the difference between - vg_sound_pate() and vg_sound_paus() - vg_sound_catb() and vg_sound_cont() just replace in the program vg_sound_pate() with vg_sound_paus() and vg_sound_catb() with vg_sound_cont() and run it. (Comment out the "#define PATE" value in the program). The whole program tut-sound2.c
[Previous] - [Index] - [Next]