Example #1
0
static void *stream_audio(ALLEGRO_THREAD *thread, void *data)
{
   ALLEGRO_EVENT_QUEUE *queue;
   VideoState *is = data;
   ALLEGRO_AUDIO_STREAM *audio_stream = is->video->audio;

   queue = al_create_event_queue();
   
   if (is->video->mixer)
      al_attach_audio_stream_to_mixer(audio_stream, is->video->mixer);
   else if (is->video->voice)
      al_attach_audio_stream_to_voice(audio_stream, is->video->voice);
   else
      al_attach_audio_stream_to_mixer(audio_stream, al_get_default_mixer());

   al_register_event_source(queue,
      al_get_audio_stream_event_source(audio_stream));

   while (1) {
      ALLEGRO_EVENT event;
      al_wait_for_event(queue, &event);

      if (event.type == ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT) {
         void *buf = al_get_audio_stream_fragment(audio_stream);
         if (!buf)
            continue;
         audio_callback(is, buf, AUDIO_BUFFER_SIZE);
         al_set_audio_stream_fragment(audio_stream, buf);
      }
   }

   return thread;
}
Example #2
0
void Audio::PlayMusic( std::string Filename, bool Loop )
{
	if( audioVoice == 0 || audioMixer == 0 )
	{
		return;
	}

	if( musicStream != nullptr )
	{
		StopMusic();
	}

	// Only play if Music is set
	if( FRAMEWORK->Settings->GetQuickBooleanValue( "Audio.Music", true ) )
	{

#ifdef WRITE_LOG
		fprintf( FRAMEWORK->LogFile, "Framework: Start audio file %s\n", Filename.c_str() );
#endif
		musicStream = al_load_audio_stream( Filename.c_str(), 4, 2048 );
		if( musicStream != nullptr )
		{
			al_attach_audio_stream_to_mixer( musicStream, audioMixer );
			al_set_audio_stream_playmode( musicStream, ( Loop ? ALLEGRO_PLAYMODE_LOOP : ALLEGRO_PLAYMODE_ONCE ) );
			FRAMEWORK->RegisterEventSource( al_get_audio_stream_event_source( musicStream ) );
			al_set_audio_stream_playing( musicStream, true );
		} else {
#ifdef WRITE_LOG
			fprintf( FRAMEWORK->LogFile, "Framework: Could not load music '%s'\n", Filename.c_str() );
#endif
		}

	}
}
Example #3
0
File: audio.c Project: EQ4/MSF
void init_audio(void)
{
	al_reserve_samples(num_samples); // Sets up the default mixer
	// Set up the audio stream and mixer attachment
	if (stream)
	{
		if (al_get_mixer_attached(al_get_default_mixer()))
		{
			al_detach_mixer(al_get_default_mixer());
		}
		al_destroy_audio_stream(stream);
	}

	stream = al_create_audio_stream(
		num_fragments,
		size_fragment,
		audio_rate,
		AUDIO_DEPTH,
		CHANNEL_CONF);

	al_attach_audio_stream_to_mixer(stream, al_get_default_mixer());

	al_register_event_source(event_queue, 
		al_get_audio_stream_event_source(stream));

}
Example #4
0
void SoundManager::PlayMusic(int num, bool loop)
{
	DestroyMusic();
	if(num==-1)
		return;
	else if(num==0)
		music = al_load_audio_stream("music/menu.ogg", 4, 2048);
	else if(num==1)
		music = al_load_audio_stream("music/level1.ogg", 4, 2048);

	if(music==NULL)
	{
		al_show_native_message_box(DisplayManager::GetInstance().GetDisplay(),
			"Error!", "SoundManager", "Couldn't load music", "ok sok", ALLEGRO_MESSAGEBOX_ERROR);
		return;
	}

	if(music==NULL)
		return;

	al_set_audio_stream_loop_secs(music, .0f, al_get_audio_stream_length_secs(music));
	if(loop)
		al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_LOOP);
	else
		al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_ONCE);
	al_attach_audio_stream_to_mixer(music, mixer);
	al_attach_mixer_to_voice(mixer,voice);

}
Example #5
0
int main(int argc, char * argv[])
{
   ALLEGRO_CONFIG *config;
   ALLEGRO_EVENT event;
   unsigned buffer_count;
   unsigned samples;
   const char *s;

   initialize();

   if (argc < 2) {
      log_printf("This example needs to be run from the command line.\nUsage: %s {audio_files}\n", argv[0]);
      goto done;
   }

   buffer_count = 0;
   samples = 0;
   config = al_load_config_file("ex_stream_seek.cfg");
   if (config) {
      if ((s = al_get_config_value(config, "", "buffer_count"))) {
         buffer_count = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "samples"))) {
         samples = atoi(s);
      }
      al_destroy_config(config);
   }
   if (buffer_count == 0) {
      buffer_count = 4;
   }
   if (samples == 0) {
      samples = 1024;
   }

   stream_filename = argv[1];
   music_stream = al_load_audio_stream(stream_filename, buffer_count, samples);
   if (!music_stream) {
      abort_example("Stream error!\n");
   }

   loop_start = 0.0;
   loop_end = al_get_audio_stream_length_secs(music_stream);
   al_set_audio_stream_loop_secs(music_stream, loop_start, loop_end);

   al_set_audio_stream_playmode(music_stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(music_stream, al_get_default_mixer());
   al_start_timer(timer);

   while (!exiting) {
      al_wait_for_event(queue, &event);
      event_handler(&event);
   }

done:
   myexit();
   al_destroy_display(display);
   close_log(true);
   return 0;
}
bool GameLogic::LoadAssets() {

    Bitmap.Logo = al_load_bitmap("assets/images/daklutz.png");
    Bitmap.Title = al_load_bitmap("assets/images/Bitmap.Title.png");
    if(!Bitmap.Title || !Bitmap.Logo) {
        fprintf(stderr, "Failed to load image files!\n");
        return false;
    }
	if(Debug) { fprintf(stderr, "Bitmaps loaded.\n"); }

	// actually load the font, I loaded the same font at different sizes.
    Font.Small = al_load_font("assets/fonts/Geo-Regular.ttf", 24, 0);
    Font.Medium = al_load_font("assets/fonts/Geo-Regular.ttf", 38, 0);
    Font.Big = al_load_font("assets/fonts/Geo-Regular.ttf", 70, 0);
	if(!Font.Small || !Font.Medium || !Font.Big) {
		fprintf(stderr, "Failed to load fonts!\n");
        return false;
    }

	if (!al_reserve_samples(2)) {
        fprintf(stderr, "Could not reserve samples!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Samples reserved.\n"); }

	Sound.HitWall = al_load_sample("assets/sounds/wall_collision.ogg");
    Sound.HitPaddle = al_load_sample("assets/sounds/paddle_collision.ogg");
    Sound.BackgroundMusic = al_load_audio_stream("assets/sounds/Sound.BackgroundMusic-tech.ogg", 4, 2048);
    if (!Sound.HitWall || !Sound.HitPaddle || !Sound.BackgroundMusic) {
        fprintf(stderr, "Failed to load sound files!\n");
        return false;
    }
	if(Debug) { fprintf(stderr, "Sound files loaded.\n"); }

	if(!al_attach_audio_stream_to_mixer(Sound.BackgroundMusic, Mixer) ) {
        fprintf(stderr, "Failed to attach stream to default Mixer!\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Stream attached to Mixer.\n"); }

    if(!al_set_mixer_playing(Mixer, true)) {
        fprintf(stderr, "Failed to play Mixer!\n");
    }
    if(Debug) { fprintf(stderr, "Mixer playing.\n"); }

    if(!al_set_audio_stream_playmode(Sound.BackgroundMusic, ALLEGRO_PLAYMODE_LOOP)) {
        fprintf(stderr, "Failed to loop stream!\n");
    }
    if(Debug) { fprintf(stderr, "Stream is set to loop.\n"); }

    if(!al_set_audio_stream_playing(Sound.BackgroundMusic, true)) {
        fprintf(stderr, "Failed to play stream!\n");
    }
    if(Debug) { fprintf(stderr, "Stream playing.\n"); }


	return true;
}
int main(int argc, char * argv[])
{
   ALLEGRO_CONFIG *config;
   ALLEGRO_EVENT event;
   unsigned buffer_count;
   unsigned samples;
   const char *s;

   if (argc < 2) {
      printf("Usage: ex_stream_seek <filename>\n");
      return -1;
   }

   if (!initialize())
      return 1;

   buffer_count = 0;
   samples = 0;
   config = al_load_config_file("ex_stream_seek.cfg");
   if (config) {
      if ((s = al_get_config_value(config, "", "buffer_count"))) {
         buffer_count = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "samples"))) {
         samples = atoi(s);
      }
      al_destroy_config(config);
   }
   if (buffer_count == 0) {
      buffer_count = 4;
   }
   if (samples == 0) {
      samples = 1024;
   }

   stream_filename = argv[1];
   music_stream = al_load_audio_stream(stream_filename, buffer_count, samples);
   if (!music_stream) {
      printf("Stream error!\n");
      return 1;
   }

   loop_start = 0.0;
   loop_end = al_get_audio_stream_length_secs(music_stream);
   al_set_audio_stream_loop_secs(music_stream, loop_start, loop_end);

   al_set_audio_stream_playmode(music_stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(music_stream, al_get_default_mixer());
   al_start_timer(timer);

   while (!exiting) {
      al_wait_for_event(queue, &event);
      event_handler(&event);
   }

   myexit();
   return 0;
}
Example #8
0
void playBGM_Stream(const char *str)
{
    if (!str)
        return;
    stream = al_load_audio_stream(str, 2, 1024);
    if (!stream)
        return;
    al_set_audio_stream_playing(stream, true);
    al_set_audio_stream_playmode(stream, ALLEGRO_PLAYMODE_LOOP);
    al_attach_audio_stream_to_mixer(stream, al_get_default_mixer());
}
bool AllegroMusicSample5::Load( const std::string & path )
{
	if ( m_pInstance )
	{
		al_detach_audio_stream( m_pInstance );
		al_destroy_audio_stream( m_pInstance );
	}

	m_pInstance = al_load_audio_stream( path.c_str(), 10, 1024 );
	if ( m_pInstance )
		al_attach_audio_stream_to_mixer( m_pInstance,  ((AllegroSound5&)GetSound()).GetMusicMixer() );

	return ( m_pInstance != 0 );
}
Example #10
0
bool
reload_sound(sound_t* sound)
{
	ALLEGRO_AUDIO_STREAM* new_stream;

	if (!(new_stream = al_load_audio_stream(sound->path, 4, 1024)))
		return false;
	if (sound->stream != NULL) {
		al_set_audio_stream_playing(sound->stream, false);
		al_destroy_audio_stream(sound->stream);
	}
	sound->stream = new_stream;
	al_set_audio_stream_gain(sound->stream, 1.0);
	al_attach_audio_stream_to_mixer(sound->stream, al_get_default_mixer());
	al_set_audio_stream_playing(sound->stream, false);
	return true;
}
Example #11
0
void playMusicOnce(const char *filename)
{

    /* play music only once in background, terminating old music */

    ALLEGRO_PLAYMODE loop = ALLEGRO_PLAYMODE_ONCE;
    al_stop_samples();
    if (music != NULL)
    {
      al_drain_audio_stream(music);
      al_destroy_audio_stream(music);
    }
    music = al_load_audio_stream(filename, 4, 2048);
    al_set_audio_stream_playmode(music, loop);
    al_attach_audio_stream_to_mixer(music, mixer);

}
Example #12
0
void FillPage(struct Game *game, int page) {
	char filename[30] = { };
	sprintf(filename, "intro/%d.flac", page);

	game->intro.audiostream = al_load_audio_stream(GetDataFilePath(filename), 4, 1024);
	al_attach_audio_stream_to_mixer(game->intro.audiostream, game->audio.voice);
	al_set_audio_stream_playing(game->intro.audiostream, false);
	al_set_audio_stream_gain(game->intro.audiostream, 1.75);

	al_set_target_bitmap(game->intro.table);
	float y = 0.2;
	float oldx = -1;
	void draw_text(int page, char* text) {
		float x = 0.45;
		if (page!=oldx) { y=0.2; oldx=page; }
		al_draw_text_with_shadow(game->intro.font, al_map_rgb(255,255,255), game->viewportWidth*x, game->viewportHeight*y, ALLEGRO_ALIGN_LEFT, text);
		y+=0.07;
	}
Example #13
0
bool Letter(struct Game *game, struct TM_Action *action, enum TM_ActionState state) {
	if (state == TM_ACTIONSTATE_INIT) {
		float* f = (float*)malloc(sizeof(float));
		*f = 0;
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)malloc(sizeof(ALLEGRO_AUDIO_STREAM*));
		*stream = al_load_audio_stream(GetDataFilePath(GetLevelFilename(game, "levels/?/letter.flac")), 4, 1024);
		al_attach_audio_stream_to_mixer(*stream, game->audio.voice);
		al_set_audio_stream_playing(*stream, false);
		al_set_audio_stream_gain(*stream, 2.00);
		action->arguments = TM_AddToArgs(action->arguments, (void*)f);
		action->arguments = TM_AddToArgs(action->arguments, (void*)stream);
		action->arguments->next->next = NULL;
	} else if (state == TM_ACTIONSTATE_DESTROY) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, false);
		al_destroy_audio_stream(*stream);
		free(action->arguments->next->value);
		free(action->arguments->value);
		TM_DestroyArgs(action->arguments);
	} else if (state == TM_ACTIONSTATE_DRAW) {
		float* f = (float*)action->arguments->value;
		al_draw_tinted_bitmap(game->level.letter, al_map_rgba(*f,*f,*f,*f), (game->viewportWidth-al_get_bitmap_width(game->level.letter))/2.0, al_get_bitmap_height(game->level.letter)*-0.05, 0);
		return false;
	} else if (state == TM_ACTIONSTATE_PAUSE) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, false);
	}	else if ((state == TM_ACTIONSTATE_RESUME) || (state == TM_ACTIONSTATE_START)) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, true);
	}
	if (state != TM_ACTIONSTATE_RUNNING) return false;

	float* f = (float*)action->arguments->value;
	*f+=5;
	if (*f>255) *f=255;
	al_draw_tinted_bitmap(game->level.letter, al_map_rgba(*f,*f,*f,*f), (game->viewportWidth-al_get_bitmap_width(game->level.letter))/2.0, al_get_bitmap_height(game->level.letter)*-0.05, 0);
	struct ALLEGRO_KEYBOARD_STATE keyboard;
	al_get_keyboard_state(&keyboard);
	// FIXME: do it the proper way
	if (al_key_down(&keyboard, ALLEGRO_KEY_ENTER)) {
		return true;
	}
	return false;
}
bool StreamResource::load(void)
{
   if (!al_is_audio_installed()) {
      debug_message("Skipped loading stream %s\n", filename.c_str());
      return true;
   }

   stream = al_load_audio_stream(filename.c_str(), 4, 1024);
   if (!stream) {
       debug_message("Error creating stream\n");
       return false;
   }

   al_set_audio_stream_playing(stream, false);
   al_set_audio_stream_playmode(stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(stream, al_get_default_mixer());

   return true;
}
Example #15
0
void Framework::PlayMusic( std::string Filename, ALLEGRO_PLAYMODE Mode )
{
#ifdef WRITE_LOG
  printf( "Framework: Play Music '%s'\n", Filename.c_str() );
#endif

	if( voice != 0 )
	{
		musicStream = audioMgr->GetMusic( Filename );
		if( musicStream != 0 )
    {
      al_set_audio_stream_playmode( musicStream, Mode );
      al_attach_audio_stream_to_mixer( musicStream, mixer );
      al_set_audio_stream_playing( musicStream, true );
    } else {
#ifdef WRITE_LOG
      printf( "Framework: Could not load music '%s'\n", Filename.c_str() );
#endif
    }
	}
}
Example #16
0
void menuLoop()
{
    bool redraw = true;
    al_start_timer(timer);

    al_attach_audio_stream_to_mixer(music, al_get_default_mixer());
    al_set_audio_stream_playing(music, true);
    al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_LOOP);

    while (!menuDone) {
        ALLEGRO_EVENT event;
        al_wait_for_event(eventMenuQueue, &event);

         if (event.type == ALLEGRO_EVENT_TIMER) {
            redraw = true;
            //update_logic();
        }
        else if (event.type == ALLEGRO_EVENT_KEY_DOWN) {
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
                menuDone = true;
            }
            if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) {
                changeGameState(Game);
            }
            if (event.keyboard.keycode == ALLEGRO_KEY_UP){
                changeGameState(Menu);
            }
            //get_user_input();
        }

        if (redraw && al_is_event_queue_empty(eventMenuQueue)) {
            redraw = false;
            al_clear_to_color(al_map_rgb(0, 0, 0));
            al_draw_tinted_bitmap(background, al_map_rgba(255, 255, 255, 255), 0, 0, 0);
            al_draw_text(font, al_map_rgb(0, 0, 0), 0, 0, 0, "BREGA HERO");
            //update_graphics();
            al_flip_display();
        }
    }
}
Example #17
0
void playMusic(const char *filename)
{

    /* play music in background, on loop - unpause if music is already playing */
    if (isMusicPaused())
    {
        unPauseMusic();
        return;
    }

    /* music not playing, start over from beginning */
    ALLEGRO_PLAYMODE loop = ALLEGRO_PLAYMODE_LOOP;
    al_stop_samples();
    if (music != NULL)
    {
      al_drain_audio_stream(music);
      al_destroy_audio_stream(music);
    }
    music = al_load_audio_stream(filename, 4, 2048);
    al_set_audio_stream_playmode(music, loop);
    al_attach_audio_stream_to_mixer(music, mixer);

}
Example #18
0
int main(int argc, char **argv)
{
   ALLEGRO_AUDIO_RECORDER *r;
   ALLEGRO_AUDIO_STREAM *s;
   
   ALLEGRO_EVENT_QUEUE *q;
   ALLEGRO_DISPLAY *d;
   ALLEGRO_FILE *fp = NULL;
   ALLEGRO_PATH *tmp_path = NULL;
      
   int prev = 0;
   bool is_recording = false;
   
   int n = 0; /* number of samples written to disk */
   
   (void) argc;
   (void) argv;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }
   
   if (!al_init_primitives_addon()) {
      abort_example("Unable to initialize primitives addon");
   }
      
   if (!al_install_keyboard()) {
      abort_example("Unable to install keyboard");
   }
      
   if (!al_install_audio()) {
      abort_example("Unable to initialize audio addon");
   }
   
   if (!al_init_acodec_addon()) {
      abort_example("Unable to initialize acodec addon");
   }
   
   /* Note: increasing the number of channels will break this demo. Other
    * settings can be changed by modifying the constants at the top of the
    * file.
    */
   r = al_create_audio_recorder(1000, samples_per_fragment, frequency,
      audio_depth, ALLEGRO_CHANNEL_CONF_1);
   if (!r) {
      abort_example("Unable to create audio recorder");
   }
   
   s = al_create_audio_stream(playback_fragment_count,
      playback_samples_per_fragment, frequency, audio_depth,
      ALLEGRO_CHANNEL_CONF_1);      
   if (!s) {
      abort_example("Unable to create audio stream");
   }
      
   al_reserve_samples(0);
   al_set_audio_stream_playing(s, false);
   al_attach_audio_stream_to_mixer(s, al_get_default_mixer());
      
   q = al_create_event_queue();
   
   /* Note: the following two options are referring to pixel samples, and have
    * nothing to do with audio samples. */
   al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST);
   al_set_new_display_option(ALLEGRO_SAMPLES, 8, ALLEGRO_SUGGEST);
   
   d = al_create_display(320, 256);
   if (!d) {
      abort_example("Error creating display\n");
   }
      
   al_set_window_title(d, "SPACE to record. P to playback.");
   
   al_register_event_source(q, al_get_audio_recorder_event_source(r));
   al_register_event_source(q, al_get_audio_stream_event_source(s));
   al_register_event_source(q, al_get_display_event_source(d));
   al_register_event_source(q, al_get_keyboard_event_source());
   
   al_start_audio_recorder(r);
   
   while (true) {
      ALLEGRO_EVENT e;

      al_wait_for_event(q, &e);
       
      if (e.type == ALLEGRO_EVENT_AUDIO_RECORDER_FRAGMENT) {
         /* We received an incoming fragment from the microphone. In this
          * example, the recorder is constantly recording even when we aren't
          * saving to disk. The display is updated every time a new fragment
          * comes in, because it makes things more simple. If the fragments
          * are coming in faster than we can update the screen, then it will be
          * a problem.
          */          
         ALLEGRO_AUDIO_RECORDER_EVENT *re = al_get_audio_recorder_event(&e);
         audio_buffer_t input = (audio_buffer_t) re->buffer;
         int sample_count = re->samples; 
         const int R = sample_count / 320;
         int i, gain = 0;
         
         /* Calculate the volume, and display it regardless if we are actively
          * recording to disk. */
         for (i = 0; i < sample_count; ++i) {
            if (gain < abs(input[i] - sample_center))
               gain = abs(input[i] - sample_center);
         }
        
         al_clear_to_color(al_map_rgb(0,0,0));
        
         if (is_recording) {
            /* Save raw bytes to disk. Assumes everything is written
             * succesfully. */
            if (fp && n < frequency / (float) samples_per_fragment * 
               max_seconds_to_record) {
               al_fwrite(fp, input, sample_count * sample_size);
               ++n;
            }

            /* Draw a pathetic visualization. It draws exactly one fragment
             * per frame. This means the visualization is dependent on the 
             * various parameters. A more thorough implementation would use this
             * event to copy the new data into a circular buffer that holds a
             * few seconds of audio. The graphics routine could then always
             * draw that last second of audio, which would cause the
             * visualization to appear constant across all different settings.
             */
            for (i = 0; i < 320; ++i) {
               int j, c = 0;
               
               /* Take the average of R samples so it fits on the screen */
               for (j = i * R; j < i * R + R && j < sample_count; ++j) {
                  c += input[j] - sample_center;
               }
               c /= R;
               
               /* Draws a line from the previous sample point to the next */
               al_draw_line(i - 1, 128 + ((prev - min_sample_val) /
                  (float) sample_range) * 256 - 128, i, 128 +
                  ((c - min_sample_val) / (float) sample_range) * 256 - 128,
                  al_map_rgb(255,255,255), 1.2);
               
               prev = c;
            }
         }
         
         /* draw volume bar */
         al_draw_filled_rectangle((gain / (float) max_sample_val) * 320, 251,
            0, 256, al_map_rgba(0, 255, 0, 128));
            
         al_flip_display();
      }
      else if (e.type == ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT) {
         /* This event is received when we are playing back the audio clip.
          * See ex_saw.c for an example dedicated to playing streams.
          */
         if (fp) {
            audio_buffer_t output = al_get_audio_stream_fragment(s);
            if (output) {
               /* Fill the buffer from the data we have recorded into the file.
                * If an error occurs (or end of file) then silence out the
                * remainder of the buffer and stop the playback.
                */
               const size_t bytes_to_read =
                  playback_samples_per_fragment * sample_size;
               size_t bytes_read = 0, i;
               
               do {
                  bytes_read += al_fread(fp, (uint8_t *)output + bytes_read,
                     bytes_to_read - bytes_read);                  
               } while (bytes_read < bytes_to_read && !al_feof(fp) &&
                  !al_ferror(fp));
               
               /* silence out unused part of buffer (end of file) */
               for (i = bytes_read / sample_size;
                  i < bytes_to_read / sample_size; ++i) {
                     output[i] = sample_center;
               }
               
               al_set_audio_stream_fragment(s, output);
               
               if (al_ferror(fp) || al_feof(fp)) {
                  al_drain_audio_stream(s);
                  al_fclose(fp);
                  fp = NULL;
               }
            }
         }
      }      
      else if (e.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if (e.type == ALLEGRO_EVENT_KEY_CHAR) {
         if (e.keyboard.unichar == 27) {
            /* pressed ESC */
            break;
         }
         else if (e.keyboard.unichar == ' ') {
            if (!is_recording) {
               /* Start the recording */
               is_recording = true;
               
               if (al_get_audio_stream_playing(s)) {
                  al_drain_audio_stream(s);
               }
               
               /* Reuse the same temp file for all recordings */
               if (!tmp_path) {
                  fp = al_make_temp_file("alrecXXX.raw", &tmp_path);
               }
               else {
                  if (fp) al_fclose(fp);
                  fp = al_fopen(al_path_cstr(tmp_path, '/'), "w");
               }
               
               n = 0;
            }
            else {
               is_recording = false;
               if (fp) {
                  al_fclose(fp);
                  fp = NULL;
               }
            }
         }
         else if (e.keyboard.unichar == 'p') {
            /* Play the previously recorded wav file */
            if (!is_recording) {
               if (tmp_path) {
                  fp = al_fopen(al_path_cstr(tmp_path, '/'), "r");
                  if (fp) {
                     al_set_audio_stream_playing(s, true);
                  }
               }
            }
         }
      }
   }
   
   /* clean up */
   al_destroy_audio_recorder(r);
   al_destroy_audio_stream(s);
      
   if (fp)
      al_fclose(fp);
      
   if (tmp_path) {
      al_remove_filename(al_path_cstr(tmp_path, '/'));
      al_destroy_path(tmp_path);
   }
   
   return 0;
}
void InvestigationScene::setupScene() {
    
    std::vector<Point> positions;
    positions.push_back(pointMake(32, 48));
    positions.push_back(pointMake(34, 48));
    positions.push_back(pointMake(36, 48));
    positions.push_back(pointMake(38, 48));
    positions.push_back(pointMake(40, 49));
    positions.push_back(pointMake(40, 51));
    positions.push_back(pointMake(40, 53));
    positions.push_back(pointMake(30, 49));
    positions.push_back(pointMake(30, 51));
    positions.push_back(pointMake(32, 52));
    
    const char *fontFile = "res/AveriaSerif-Regular.ttf";
    
    font = al_load_font(fontFile, 18, 0);
    if (!font) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", fontFile);
    }
    
    fontBig = al_load_font(fontFile, 26, 0);
    if (!fontBig) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", fontFile);
    }
    
    searchSound = al_load_sample("res/search.wav");
    if (!searchSound) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", "res/search.wav");
    }
    
    clickSound = al_load_sample("res/click.wav");
    if (!clickSound) {
        Director::getInstance()->abortWithMessage("%s not found or failed to load\n", "res/click.wav");
    }
    
    std::vector<TilemapLayer *> layers = TilemapLayer::parseTMXFile("res/mansion.tmx");
    std::vector<TilemapLayer *>::iterator it;
    
    TilemapLayer *firstLayer = layers[0];
    
    camera = new Camera(800, 600, firstLayer->getBoundsSize().width, firstLayer->getBoundsSize().height);
    
    for (it = layers.begin(); it < layers.end(); ++it) {
        
        TilemapLayer *layer = (TilemapLayer *) *it;
        layer->setCamera(camera);
        addToDisplayList(layer);
        
        if (layer->isCollision()) {
            collision = layer;
        }
    }
            
    playerSprite = new Spritesheet("res/professor_walk_cycle_no_hat.png", 64, 64);
    playerSprite->setTag(PLAYER_SPRITE_TAG);
    playerSprite->setCamera(camera);
    playerSprite->setPosition(pointMake(35 * 32, 50 * 32));
    playerSprite->setAnchorPoint(pointMake(0.5, 0.9));
    playerSprite->setAutoZOrder(true);
    addToDisplayList(playerSprite);
    
    mysterySeed = 0;
    
    do {
        
        mysteryTime = 0;
        mysterySeed = time(0);
        
        mystery = new Mystery("res/mansion.xml", mysterySeed, collision->getData(), collision->getSize().width, collision->getSize().height);
        
        while (!mystery->ended && mysteryTime < MAX_MYSTERY_DURATION) {
            mystery->step();
            mysteryTime++;
        }
        
        if (!mystery->ended) {
            delete mystery;
            mystery = NULL;
        }
        
    } while (mystery == NULL);
                    
    printf("Case seed: %d Total duration: %ld %s\n", mysterySeed, mysteryTime, timeToString(mysteryTime, true).c_str());
    
    std::vector<Character *> characters = mystery->getCharacters();
    std::vector<Character *>::iterator itChars;
    
    int i = 0;
    
    for (itChars = characters.begin(); itChars < characters.end(); ++itChars) {
        
        Character *character = (Character *) *itChars;
        
        int frame = i * 2;
        
        if (!character->dead) {
            int idx = rand() % positions.size();
            Point pos = positions[idx];
            
            character->position = pos;
            
            positions.erase(positions.begin() + idx);
        } else {
            frame++;
        }
        
        Spritesheet *sprite = new Spritesheet("res/characters.png", 64, 64);
        sprite->setTag(character->tag);
        sprite->setCamera(camera);
        sprite->setAnchorPoint(pointMake(0.5, 0.9));
        sprite->setAutoZOrder(true);
        sprite->setFrame(frame);
        
        Rect tileRect = collision->getTileRect(character->position.x, character->position.y);
        sprite->setPosition(rectMidPoint(tileRect));
        
        addToDisplayList(sprite);        
        
        i++;
    }
    
    std::vector<POI *>::iterator itWeapons;
    
    i = 0;
    
    for (itWeapons = mystery->weapons.begin(); itWeapons < mystery->weapons.end(); ++itWeapons) {
        
        POI *weapon = (POI *) *itWeapons;
        
        Spritesheet *sprite = new Spritesheet("res/weapons.png", 32, 32);
        sprite->setTag(i + 20);
        sprite->setFrame(i);
        sprite->setCamera(camera);
        sprite->setAnchorPoint(pointMake(0.5, 0.5));
        sprite->setZOrder(400);
        
        Rect tileRect = collision->getTileRect(weapon->position.x, weapon->position.y);
        sprite->setPosition(rectMidPoint(tileRect));
        
        addToDisplayList(sprite);
        
        i++;
    }
    
    actionButton = new Button("action", font, BTN_TXT_COLOR, "res/btn_action.png", "res/btn_action_pressed.png");
    actionButton->setZOrder(500);
    actionButton->setAnchorPoint(pointMake(0.5, 1));
    actionButton->setPosition(pointMake(400, 400));
    actionButton->setCamera(camera);
    actionButton->setHandler(this);
    
    addToDisplayList(actionButton);
    
    Spritesheet *bkgRoomLabel = new Spritesheet("res/bkg_room_name.png");
    bkgRoomLabel->setAnchorPoint(pointMake(0.5, 0.5));
    bkgRoomLabel->setPosition(pointMake(400, 40));
    bkgRoomLabel->setZOrder(501);
    
    addToDisplayList(bkgRoomLabel);
    
    currentRoomLabel = new Label("room", font, al_map_rgb(0, 0, 0));
    currentRoomLabel->setAnchorPoint(pointMake(0.5, 0.5));
    currentRoomLabel->setPosition(bkgRoomLabel->getPosition());
    currentRoomLabel->setZOrder(502);
    
    addToDisplayList(currentRoomLabel);
    
    Spritesheet *bkgWeaponLabel = new Spritesheet("res/bkg_room_name.png");
    bkgWeaponLabel->setAnchorPoint(pointMake(0.5, 0.5));
    bkgWeaponLabel->setPosition(pointMake(720, 40));
    bkgWeaponLabel->setZOrder(501);
    
    addToDisplayList(bkgWeaponLabel);
    
    crimeWeaponLabel = new Label("No weapon", font, al_map_rgb(0, 0, 0));
    crimeWeaponLabel->setAnchorPoint(pointMake(0.5, 0.5));
    crimeWeaponLabel->setPosition(bkgWeaponLabel->getPosition());
    crimeWeaponLabel->setZOrder(502);
    
    addToDisplayList(crimeWeaponLabel);
    
    Spritesheet *bkgAccusationLabel = new Spritesheet("res/bkg_room_name.png");
    bkgAccusationLabel->setAnchorPoint(pointMake(0.5, 0.5));
    bkgAccusationLabel->setPosition(pointMake(80, 40));
    bkgAccusationLabel->setZOrder(501);
    
    addToDisplayList(bkgAccusationLabel);
    
    char buf[100];
    sprintf(buf, "%d accusations left", MAX_ACCUSATIONS);
    
    accusationsLabel = new Label(buf, font, al_map_rgb(0, 0, 0), 120);
    accusationsLabel->setAnchorPoint(pointMake(0.5, 0.5));
    accusationsLabel->setPosition(bkgAccusationLabel->getPosition());
    accusationsLabel->setZOrder(502);
    
    addToDisplayList(accusationsLabel);
    
    bkgQuestion = new Spritesheet("res/bkg_question.png");
    bkgQuestion->setAnchorPoint(pointMake(0.5, 0.5));
    bkgQuestion->setPosition(pointMake(400, 300));
    bkgQuestion->setZOrder(503);
    bkgQuestion->setVisible(false);
        
    addToDisplayList(bkgQuestion);
    
    questionLabel = new Label("question", font, al_map_rgb(0, 0, 0), 350);
    questionLabel->setAnchorPoint(pointMake(0.5, 0.5));
    questionLabel->setPosition(pointMake(400, 120));
    questionLabel->setZOrder(504);
    questionLabel->setVisible(false);
    
    addToDisplayList(questionLabel);
    
    whenLabel = new Label("00:00 and 00:15", fontBig, al_map_rgb(0, 0, 0));
    whenLabel->setAnchorPoint(pointMake(0.5, 0.5));
    whenLabel->setPosition(pointMake(400, 300));
    whenLabel->setZOrder(504);
    whenLabel->setVisible(false);
    
    addToDisplayList(whenLabel);
    
    askQuestionButton = new Button("Ask", font, BTN_TXT_COLOR, "res/btn_med.png", "res/btn_med_pressed.png");
    askQuestionButton->setZOrder(504);
    askQuestionButton->setAnchorPoint(pointMake(0.5, 0.5));
    askQuestionButton->setPosition(pointMake(480, 490));
    askQuestionButton->setHandler(this);
    askQuestionButton->setVisible(false);
    askQuestionButton->setEnabled(false);
    
    addToDisplayList(askQuestionButton);
    
    cancelQuestionButton = new Button("Cancel", font, BTN_TXT_COLOR, "res/btn_med.png", "res/btn_med_pressed.png");
    cancelQuestionButton->setZOrder(504);
    cancelQuestionButton->setAnchorPoint(pointMake(0.5, 0.5));
    cancelQuestionButton->setPosition(pointMake(300, 490));
    cancelQuestionButton->setHandler(this);
    cancelQuestionButton->setVisible(false);
    cancelQuestionButton->setEnabled(false);
    
    addToDisplayList(cancelQuestionButton);
    
    bkgSpeech = new Spritesheet("res/speech.png");
    bkgSpeech->setAnchorPoint(pointMake(0.35, 1));
    bkgSpeech->setCamera(camera);
    bkgSpeech->setZOrder(503);
    bkgSpeech->setVisible(false);
    
    addToDisplayList(bkgSpeech);
    
    speechLabel = new Label("speech", font, al_map_rgb(0, 0, 0), 280);
    speechLabel->setAnchorPoint(pointMake(0.5, 0.5));
    speechLabel->setCamera(camera);
    speechLabel->setZOrder(504);
    speechLabel->setVisible(false);
    
    addToDisplayList(speechLabel);
    
    speechCountLabel = new Label("1/1", font, al_map_rgb(0, 0, 0));
    speechCountLabel->setAnchorPoint(pointMake(1, 0.5));
    speechCountLabel->setCamera(camera);
    speechCountLabel->setZOrder(504);
    speechCountLabel->setVisible(false);
    
    addToDisplayList(speechCountLabel);
    
    speechButton = new Button(bkgSpeech->getFrameSize());
    speechButton->setAnchorPoint(bkgSpeech->getAnchorPoint());
    speechButton->setCamera(camera);
    speechButton->setZOrder(504);
    speechButton->setEnabled(false);
    speechButton->setHandler(this);
    
    addToDisplayList(speechButton);
    
    camera->setCenter(playerSprite->getPosition());
    
    activeCharacter = NULL;
    activePOI = NULL;
    currentRoom = NULL;
    crimeWeapon = NULL;
    
    accusationsLeft = MAX_ACCUSATIONS;
    questionsAsked = 0;
    
    moving = pointMake(0, 0);
    moveDir = 0;
    curFrame = 0;
    
    endScene = false;
    debug = false;
    
    currentFilter.timeStart = 0;
    currentFilter.timeEnd = QUESTION_INTERVAL;
    
    std::string msg;
    msg.append(mystery->victim->name);
    msg.append("'s body was found around ");
    msg.append(timeToString(mystery->corpseFoundTime + START_TIME, false));
    msg.append(" in the ");
    msg.append(mystery->corpseFoundRoom->name);
    msg.append(".");
    
    ModalDialog *dialog = new ModalDialog(msg.c_str(), font, "OK", NULL);
    dialog->setHandler(this);
    dialog->showInScene(this, 1000);
    
    music = al_load_audio_stream("res/mystery.ogg", 4, 2048);
    al_set_audio_stream_playmode(music, ALLEGRO_PLAYMODE_LOOP);
    al_attach_audio_stream_to_mixer(music, al_get_default_mixer());
    
    inDialogue = false;
    inputLocked = true;
    
    investigationStartTime = time(0);
}
int main() {
  bool menu = true;
  char pontuacao[100];
  char vida[100];
  ALLEGRO_COLOR  font_color;
  ALLEGRO_FONT *font,*font2;
  ALLEGRO_AUDIO_STREAM *musica = NULL;
  
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("erro na inicializacao da camera\n");
  int x = 0, y =  0;
  int largura = cam->largura;
  int altura = cam->altura;
  int fps = 0,tempo = 5;
  int ndisco = 9;
 
  if(!al_init())
    erro("erro na inicializacao do allegro\n");

  if(!al_init_image_addon())
    erro("erro na inicializacao do adicional de imagem\n");

  al_init_font_addon();
  al_init_ttf_addon();

    font_color = al_map_rgb(0, 0, 0);
    
    font = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 20, 0);
    font2 = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 50, 0);
    


  if(!al_init_primitives_addon())
    erro("erro na inicializacao do adicional de primitivas\n");

  ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
  if(!timer)
    erro("erro na criacao do relogio\n");

  ALLEGRO_DISPLAY *display = al_create_display(2 * largura,altura);
  if(!display)
    erro("erro na criacao da janela\n");

  ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
  if(!queue)
    erro("erro na criacao da fila\n");

   if (!al_install_audio())
    {
        fprintf(stderr, "Falha ao inicializar áudio.\n");
        return false;
    }
 
    if (!al_init_acodec_addon())
    {
        fprintf(stderr, "Falha ao inicializar codecs de áudio.\n");
        return false;
    }
    if (!al_reserve_samples(1))
    {
        fprintf(stderr, "Falha ao alocar canais de áudio.\n");
        return false;
    }

  musica = al_load_audio_stream("Audio/elementary.ogg", 4, 1024);
  if(!musica)
        erro("Erro na alocação da musica de fundo\n");

  al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
  al_set_audio_stream_playing(musica, true);

  al_register_event_source(queue, al_get_timer_event_source(timer));
  al_register_event_source(queue, al_get_display_event_source(display));

  al_start_timer(timer);
  
  unsigned char ***matriz = camera_aloca_matriz(cam);
  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);
  ALLEGRO_BITMAP *fundo = al_load_bitmap("Imagens/Elementary2.png");

  if(!fundo)
    erro("erro ao carregar Elementary.png");

  ALLEGRO_BITMAP *esquerda = al_create_sub_bitmap(buffer, 0, 0, largura, altura);
  ALLEGRO_BITMAP *direita = al_create_sub_bitmap(buffer, largura, 0, largura, altura);

  /**********/
  Disco *discos[9];
  bool perdeu = false;
  carregarDiscos(discos);
  int pontos=0,velo = 1;
  int aux1 = 1;
  int vidas = 10;
  int ultimoDisco = 0;
  int distance = 0;
  int desenhar = 0;
  int terminar = 0;
  al_set_target_bitmap(esquerda);
  al_draw_bitmap(fundo,0,0,0);
  while(1) {

    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

    switch(event.type) {
    case ALLEGRO_EVENT_TIMER:
      desenhar = 1;
      break;
    case ALLEGRO_EVENT_DISPLAY_CLOSE:
      terminar = 1;
      break;
   
    }

    if(terminar)
      break;

    if(desenhar && al_is_event_queue_empty(queue)) {
      desenhar = 0;
      camera_atualiza(cam);
      mediana(cam);
      /**********/
      al_set_target_bitmap(esquerda);
      al_draw_bitmap(fundo,0,0,0);
      
      if(!menu){
        while(aux1 <= ndisco){
          if(discos[aux1]->status == false){
            if(distance > 50 || ultimoDisco==0  ){
              printf("%d\n",aux1 );
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
              discos[aux1]->status = true;
              distance = 0;
              ultimoDisco = aux1;
              break;
            }else
             aux1++;
          }else{
              discos[aux1]->pos_y+=(10+velo);
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
            aux1++;
              
            }
        }
        distance = discos[ultimoDisco]->pos_y;
        for(aux1 = 1;aux1<ndisco;aux1++){
          if(discos[aux1]->pos_x >= x-30 && discos[aux1]->pos_x <= x+30 && discos[aux1]->pos_y >= y-30 &&  discos[aux1]->pos_y <= y+30){
            if(discos[aux1]->tipo == 2){ // Tipo do fogo(Necessario para vencer o jogo)
            pontos +=10;
            velo += 1;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }else if(discos[aux1]->tipo == 1){ //Tipo da agua(Perde o jogo se destruir esse disco)
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else if(discos[aux1]->tipo == 3){//Tipo planta(Aumenta velocidade de queda das peças)
            velo *= 2;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }

        }else if( discos[aux1]->pos_y > 480){
          if(discos[aux1]->tipo == 2){ //Tipo da agua e Planta(Não perde se deixar cair)
               discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else{
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }
        }
      }

        aux1 = 1;
      sprintf(pontuacao,"PONTUAÇÃO: %d",pontos);
      al_draw_text(font, al_map_rgb(255, 255, 255), 50, 5, 0,pontuacao);
       sprintf(vida,"VIDAS: %d",vidas);
      al_draw_text(font, al_map_rgb(255, 255, 255), 300, 5, 0,vida);
      al_flip_display();

      }
       if(perdeu){
        al_draw_text(font2, al_map_rgb(255, 0, 0), 50, 100, 0,"PONTUAÇÃO FINAL");
        sprintf(pontuacao,"%d",pontos);
        al_draw_text(font2, al_map_rgb(255, 0, 0), 250, 170, 0,pontuacao);
        al_flip_display();
        al_rest(3);
        break;
      }
       
      if(vidas == 0){
        perdeu = true;
      }

      if(menu){
        if(abrirJogo(x,y,&fps,&tempo,font,font2, font_color)){
          fundo = al_load_bitmap("Imagens/galaxia.png");
          menu = false;
        }
      }
      cameraRastreia(cam,&x,&y);
   

      al_set_target_bitmap(direita);
      camera_copia(cam, cam->quadro, direita);
      al_flip_display();
    }
  }
  al_destroy_bitmap(direita);
  al_destroy_bitmap(fundo);
  al_destroy_bitmap(esquerda);
  camera_libera_matriz(cam, matriz);
int fri = 9;
while(fri != 0){
  free(discos[fri]);
  fri--;

}


  al_stop_timer(timer);

  al_unregister_event_source(queue, al_get_display_event_source(display));
  al_unregister_event_source(queue, al_get_timer_event_source(timer));

  al_destroy_event_queue(queue);
  al_destroy_display(display);
  al_destroy_timer(timer);
  al_destroy_audio_stream(musica);
  al_shutdown_primitives_addon();
  al_shutdown_image_addon();
  al_uninstall_system();

  camera_finaliza(cam);

  return EXIT_SUCCESS;
}
Example #21
0
static void * t3f_play_music_thread(void * arg)
{
    const char * ext = NULL;
    ALLEGRO_PATH * path = NULL;
    int loop_points = 0;
    float loop_start = -1;
    float loop_end = -1;
    bool loop_disabled = false;
    const char * val = NULL;
    ALLEGRO_CONFIG * config = NULL;

    ALLEGRO_DEBUG("music thread start\n");
    t3f_music_gain = 1.0;
    al_lock_mutex(t3f_music_mutex);
    if(t3f_stream)
    {
        t3f_stop_music();
    }
    ALLEGRO_DEBUG("setting file interface\n");
    al_set_new_file_interface(t3f_music_thread_file_interface);
    t3f_stream = al_load_audio_stream(t3f_music_thread_fn, 4, 4096);
    if(!t3f_stream)
    {
        al_unlock_mutex(t3f_music_mutex);
        t3f_set_music_state(T3F_MUSIC_STATE_OFF);
        return NULL;
    }

    ALLEGRO_DEBUG("configuring music\n");
    /* look for loop data */
    path = al_create_path(t3f_music_thread_fn);
    if(path)
    {
        al_set_path_extension(path, ".ini");
        config = al_load_config_file(al_path_cstr(path, '/'));
        if(config)
        {
            val = al_get_config_value(config, "loop", "disabled");
            if(val && !strcasecmp(val, "true"))
            {
                loop_disabled = true;
            }
            if(!loop_disabled)
            {
                val = al_get_config_value(config, "loop", "start");
                if(val)
                {
                    loop_start = atof(val);
                    loop_points++;
                }
                val = al_get_config_value(config, "loop", "end");
                if(val)
                {
                    loop_end = atof(val);
                    loop_points++;
                }
            }
            val = al_get_config_value(config, "settings", "gain");
            if(val)
            {
                t3f_music_gain = atof(val);
                if(t3f_music_gain < 0.0)
                {
                    t3f_music_gain = 0;
                }
                if(t3f_music_gain > 10.0)
                {
                    t3f_music_gain = 10.0;
                }
            }
            al_destroy_config(config);
        }
        al_destroy_path(path);
    }

    if(loop_disabled)
    {
        al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_ONCE);
    }
    else
    {
        if(loop_points != 2)
        {
            /* loop entire song unless audio is MOD music */
            ext = t3f_get_music_extension(t3f_music_thread_fn);
            if(strcmp(ext, ".xm") && strcmp(ext, ".it") && strcmp(ext, ".mod") && strcmp(ext, ".s3m"))
            {
                al_set_audio_stream_loop_secs(t3f_stream, 0.0, al_get_audio_stream_length_secs(t3f_stream));
                al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_LOOP);
            }
            else
            {
                al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_LOOP);
            }
        }
        else
        {
            al_set_audio_stream_loop_secs(t3f_stream, loop_start, loop_end);
            al_set_audio_stream_playmode(t3f_stream, ALLEGRO_PLAYMODE_LOOP);
        }
    }
    ALLEGRO_DEBUG("start the music\n");
    t3f_music_volume = t3f_new_music_volume;
    al_set_audio_stream_gain(t3f_stream, t3f_music_volume * t3f_music_gain);
    al_attach_audio_stream_to_mixer(t3f_stream, al_get_default_mixer());
    al_unlock_mutex(t3f_music_mutex);
    t3f_set_music_state(T3F_MUSIC_STATE_PLAYING);
    return NULL;
}
/* return the player so you can use more advanced features if you want
   you can safely ignore the return value if all you want is to play a mod */
DUMBA5_PLAYER * dumba5_create_player(DUH * dp, int pattern, bool loop, int bufsize, int frequency, bool stereo)
{
	DUMBA5_PLAYER * player;
	ALLEGRO_CHANNEL_CONF c_conf;
	int n_channels = 2;

	/* This restriction is imposed by Allegro. */
	ASSERT(n_channels > 0);
	ASSERT(n_channels <= 2);
	
	if(!dp)
	{
		return NULL;
	}

	player = (DUMBA5_PLAYER *) malloc(sizeof(DUMBA5_PLAYER));
	if(!player)
	{
		return NULL;
	}

	player->flags = 0;
	player->bufsize = bufsize;
	player->freq = frequency;
	player->channels = n_channels;
	if(n_channels == 1)
	{
		c_conf = ALLEGRO_CHANNEL_CONF_1;
	}
	else
	{
		c_conf = ALLEGRO_CHANNEL_CONF_2;
	}

	player->stream = al_create_audio_stream(4, bufsize, frequency, ALLEGRO_AUDIO_DEPTH_INT16, c_conf);

	if(!player->stream)
	{
		free(player);
		return NULL;
	}
	al_attach_audio_stream_to_mixer(player->stream, al_get_default_mixer());

	player->sigrenderer = dumb_it_start_at_order(dp, n_channels, pattern);

	if(!player->sigrenderer)
	{
		al_destroy_audio_stream(player->stream);
		free(player);
		return NULL;
	}
	player->mutex = al_create_mutex();
	if(!player->mutex)
	{
		return NULL;
	}
	player->thread = al_create_thread(dumba5_update_thread, player);
	if(!player->thread)
	{
		return NULL;
	}

	player->volume = 1.0;
	player->silentcount = 0;
	player->duh = dp;

	return player;
}
Example #23
0
int main(int argc, char *argv[])
{

// -------- VARIÁVEIS DO JOGO --------
ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_FONT *font20 = NULL;
ALLEGRO_SAMPLE *ataque = NULL;
ALLEGRO_SAMPLE *morte_inimigo = NULL;
ALLEGRO_SAMPLE *morte_personagem = NULL;
ALLEGRO_SAMPLE *hit = NULL;
ALLEGRO_SAMPLE *item = NULL;
ALLEGRO_AUDIO_STREAM *musica = NULL;
ALLEGRO_AUDIO_STREAM *track_menu = NULL;
ALLEGRO_BITMAP *start = NULL;

bool fim = false;
bool menu = true;
int flag = 0;
bool desenha = true;
bool game_over = false;
bool teclas[] = {false, false, false, false, false, false, false};
int i;
int dificuldade;


// ___________________________________


// -------- INICIALIZAÇÃO DE OBJETOS --------
dificuldade = 0;
Personagem personagem_principal;
Projetil* balas = new Projetil [NUM_BALAS];
Projetil* balas_2 = new Projetil [NUM_BALAS];
Inimigo* inimigos = new Inimigo[NUM_INIMIGOS];
Inimigo* inimigos2 = new Inimigo [NUM_INIMIGOS];
Coracao* coracoes = new Coracao[NUM_ITENS];
Speed* speed = new Speed[NUM_ITENS];
ItemPontos* pontos = new ItemPontos[NUM_ITENS];
Estrelas estrelas_pf[NUM_PLANOS][NUM_ESTRELAS];
Selecionar select;


// __________________________________________

// -------- INICIALIZAÇÃO DA ALLEGRO E DO DISPLAY --------
    ALLEGRO_DISPLAY *display = NULL;

    if (!al_init())
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO INICIALIZAR A ALLEGRO!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    display = al_create_display(LARGURA_T, ALTURA_T);

    if (!display)
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO CRIAR O DISPLAY!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    al_set_window_title(display, "Cosmos Guardian");


// ____________________________________________________

// -------- INICIALIZAÇÃO DE ADDONS E INSTALAÇÕES --------
    al_init_primitives_addon();
    al_install_keyboard();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    al_install_audio();
    al_init_acodec_addon();

    al_reserve_samples(100);

// _______________________________________________________

// -------- CRIAÇÃO DE FILAS E DEMAIS DISPOSITIVOS --------
    fila_eventos = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);
    font20 = al_load_font("BADABB__.ttf", 20, 0);


// ________________________________________________________

// -------- REGISTRO DE SOURCES --------
    al_register_event_source(fila_eventos, al_get_display_event_source(display));
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));

// _____________________________________


// -------- FUNÇÕES INICIAIS --------
    srand(time(NULL));
    personagem_principal.InitPersonagem();

    select.InitSelecionar();

    //Inicialização de projeteis
    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].InitBalas();
        balas_2[i].InitBalas();
    }

    //Inicialização de inimigos
    for (i = 0; i < NUM_INIMIGOS; i++)
    {
        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
    }

    //Inicialização de itens
    for (i = 0; i < NUM_ITENS; i++)
    {
        coracoes[i].InitItem();
        speed[i].InitItem();
        pontos[i].InitItem();
    }

    //Inicialização do Plano de Fundo
    InitPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);

    //Setando Sons e Imagens
    select.bmp = al_load_bitmap("select.png");
    ataque = al_load_sample("laser.wav");
    morte_inimigo = al_load_sample("dead.wav");
    morte_personagem = al_load_sample("death.wav");
    hit = al_load_sample("hit.wav");
    item = al_load_sample("item.wav");
    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);
    track_menu = al_load_audio_stream("menu.ogg", 4, 1024);
    personagem_principal.bmp = al_load_bitmap("ship.png");


    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].bmp = al_load_bitmap("bala.png");
        balas_2[i].bmp = al_load_bitmap("bala.png");
    }
    for (i = 0; i < NUM_INIMIGOS; i++){
        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
    }
    start = al_load_bitmap("start.jpg");

    for (i = 0; i < NUM_ITENS; i++){
        coracoes[i].imagem = al_load_bitmap("heart.png");
        speed[i].imagem = al_load_bitmap("speed.png");
        pontos[i].imagem = al_load_bitmap("pontos.png");
    }
// __________________________________

// ----------------- LOOP PRINCIPAL -----------------
    al_start_timer(timer);

    while(!fim)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(fila_eventos, &ev);
        // -------- EVENTOS E LÓGICA DO JOGO --------
        if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            fim = true;
        }

        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_ESCAPE:
                fim = true;
                break;
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = true;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = true;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = true;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = true;
                break;
            case ALLEGRO_KEY_SPACE:
                teclas[ESPACO] = true;
                AtiraBalas(balas, NUM_BALAS, personagem_principal, personagem_principal.y + 12);
                AtiraBalas(balas_2, NUM_BALAS, personagem_principal, personagem_principal.y + 70);
                al_play_sample(ataque, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = true;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = true;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = false;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = false;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = false;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = false;
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = false;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = false;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_TIMER)
        {
            desenha = true;

            if (teclas[CIMA])
                personagem_principal.MoveCima();
            if (teclas[BAIXO])
                personagem_principal.MoveBaixo(ALTURA_T);
            if (teclas[ESQUERDA])
                personagem_principal.MoveEsquerda();
            if (teclas[DIREITA])
                personagem_principal.MoveDireita(LARGURA_T);
            if (teclas[ESPACO])
            {
                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].AtualizaBalas(0);
                    balas_2[i].AtualizaBalas(0);
                }

            }

            // Movimentação no menu
            if(menu)
            {
                al_attach_audio_stream_to_mixer(track_menu, al_get_default_mixer());
                al_set_audio_stream_playing(track_menu, true);
                if (teclas[CIMA] && select.y!=235)
                    select.y -= 70;
                if (teclas[BAIXO] && select.y!=305)
                    select.y += 70;
                if (teclas[ENTER] && select.y==235)
                {
                    menu = false;
                    al_set_audio_stream_playing(track_menu, false);
                }

            }

            // Acontecimentos do Jogo
            if(!game_over && !menu)
            {
                al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
                al_set_audio_stream_playing(musica, true);

                AtualizaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                {
                    //Gera e atualiza inimigos
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].GeraInimigos();
                        inimigos2[i].GeraInimigos();
                        inimigos[i].AtualizaInimigos();
                        inimigos[i].InimigoColidido(personagem_principal, hit);
                        inimigos2[i].AtualizaInimigos();
                        inimigos2[i].InimigoColidido(personagem_principal, hit);
                    }
                }

                //Checa colisões de projeteis

                BalaColidida(balas, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                BalaColidida(balas, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                // Faz os testes relacionado aos itens
                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].GeraItens(inimigos[i]);
                    coracoes[i].AtualizaItens();
                    coracoes[i].ItemColidido(personagem_principal, item);

                    speed[i].GeraItens(inimigos[i]);
                    speed[i].AtualizaItens();
                    speed[i].ItemColidido(personagem_principal, item);

                    pontos[i].GeraItens(inimigos[i]);
                    pontos[i].AtualizaItens();
                    pontos[i].ItemColidido(personagem_principal, item);
                }


                if ((dificuldade+1)%16 == 0) // Dificuldade aumenta a cada 15 pontos.
                {
                    for (i = 0; i < NUM_INIMIGOS; i++){
                        inimigos[i].velocidade++;
                        inimigos2[i].velocidade++;
                    }

                    dificuldade = 0;
                }

                if (personagem_principal.vidas <= 0)
                {
                    al_play_sample(morte_personagem, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                    game_over = true;
                }
            }

            // Reinicializa o jogo
            else if (!menu)
            {
                al_set_audio_stream_playing(musica, false);
                if (teclas[ENTER])
                {
                    al_destroy_audio_stream(musica);

                    personagem_principal.InitPersonagem();

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].InitBalas();
                        balas_2[i].InitBalas();
                    }


                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
                        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
                    }

                    for (i = 0; i < NUM_ITENS; i++)
                    {
                        coracoes[i].InitItem();
                        speed[i].InitItem();
                        pontos[i].InitItem();
                    }


                    personagem_principal.bmp = al_load_bitmap("ship.png");
                    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].bmp = al_load_bitmap("bala.png");
                        balas_2[i].bmp = al_load_bitmap("bala.png");
                    }
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
                        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
                        coracoes[i].imagem = al_load_bitmap("heart.png");
                        speed[i].imagem = al_load_bitmap("heart.png");
                    }

                    game_over = false;
                }
            }

        }


        // _________________________________________

        // ---------------- DESENHO ----------------

        if(desenha && al_is_event_queue_empty(fila_eventos))
        {
            desenha = false;
            // Desenhos da Tela do Menu
            if(menu)
            {
                al_draw_bitmap(start, 0, 0, 0);
                if (select.ativo)
                    al_draw_bitmap(select.bmp, select.x, select.y, 0);

                if (teclas[ENTER] && flag == 0)
                {
                    flag = 1;
                    teclas[BACKSPACE] = false;
                    select.ativo = false;
                    start = al_load_bitmap("como_jogar.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
                else if (teclas[BACKSPACE] && flag == 1)
                {
                    flag = 0;
                    select.ativo = true;
                    start = al_load_bitmap("start.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
            }
            // Jogo normal, desenho de todos os objetos
            if(!game_over && !menu)
            {
                DesenhaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                personagem_principal.DesenhaPersonagem();

                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].DesenhaBalas();
                    balas_2[i].DesenhaBalas();
                }

                for (i = 0; i < NUM_INIMIGOS; i++){
                    inimigos[i].DesenhaInimigos();
                    inimigos2[i].DesenhaInimigos();
                }

                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].DesenhaItens();
                    speed[i].DesenhaItens();
                    pontos[i].DesenhaItens();
                }


                al_draw_textf(font20, al_map_rgb(255, 255, 255), 0, 0, 0, "VIDAS: %d / PONTOS: %d", personagem_principal.vidas, personagem_principal.pontos);
            }

            //Tela de fim de jogo
            else if (!menu)
            {
                al_draw_textf(font20, al_map_rgb(255, 255, 255), LARGURA_T / 2, ALTURA_T / 2, ALLEGRO_ALIGN_CENTRE, "FIM DE JOGO. SEUS PONTOS FORAM: %d. TECLE ENTER PARA JOGAR NOVAMENTE OU ESC PARA SAIR DO JOGO.", personagem_principal.pontos);
            }

            al_flip_display();
            al_clear_to_color(al_map_rgb(0, 0, 0));
        }


        // _________________________________________
    }

// _________________________________________________

// -------- FINALIZAÇÕES DO PROGRAMA --------
    delete[] inimigos;
    delete[] inimigos2;
    delete[] balas;
    delete[] balas_2;
    delete[] coracoes;
    delete[] speed;
    delete[] pontos;

    al_destroy_bitmap(start);

    al_destroy_sample(ataque);
    al_destroy_sample(morte_inimigo);
    al_destroy_sample(morte_personagem);
    al_destroy_sample(hit);
    al_destroy_sample(item);
    al_destroy_audio_stream(musica);
    al_destroy_audio_stream(track_menu);

    al_destroy_display(display);
    al_destroy_timer(timer);
    al_destroy_font(font20);
    al_destroy_event_queue(fila_eventos);

//___________________________________________
    return 0;
}
DUMBA5_PLAYER * dumba5_start_duh_x(DUH *duh, int n_channels, long pos, float volume, long bufsize, int freq)
{
	DUMBA5_PLAYER * dp;
	ALLEGRO_CHANNEL_CONF c_conf;

	/* This restriction is imposed by Allegro. */
	ASSERT(n_channels > 0);
	ASSERT(n_channels <= 2);
	
	if(!duh)
	{
		return NULL;
	}

	dp = (DUMBA5_PLAYER *) malloc(sizeof(DUMBA5_PLAYER));
	if(!dp)
	{
		return NULL;
	}

	dp->flags = ADP_PLAYING;
	dp->bufsize = bufsize;
	dp->freq = freq;
	dp->channels = n_channels;
	if(n_channels == 1)
	{
		c_conf = ALLEGRO_CHANNEL_CONF_1;
	}
	else
	{
		c_conf = ALLEGRO_CHANNEL_CONF_2;
	}

	dp->stream = al_create_audio_stream(4, bufsize, freq, ALLEGRO_AUDIO_DEPTH_INT16, c_conf);

	if (!dp->stream) {
		free(dp);
		return NULL;
	}
	al_attach_audio_stream_to_mixer(dp->stream, al_get_default_mixer());

	dp->sigrenderer = dumb_it_start_at_order(duh, n_channels, pos);

	if (!dp->sigrenderer) {
		al_destroy_audio_stream(dp->stream);
		free(dp);
		return NULL;
	}
	dp->thread = al_create_thread(dumba5_update_thread, dp);
	if(!dp->thread)
	{
		return NULL;
	}

	dp->volume = volume;
	dp->silentcount = 0;
	dp->duh = duh;
	al_start_thread(dp->thread);

	return dp;
}
Example #25
0
int main(int argc, char *argv[])
{
   ALLEGRO_CONFIG *config;
   ALLEGRO_EVENT event;
   unsigned buffer_count;
   unsigned samples;
   const char *s;
   ALLEGRO_PLAYMODE playmode = ALLEGRO_PLAYMODE_LOOP;

   initialize();

   if (argc > 1) {
      stream_filename = argv[1];
   }

   buffer_count = 0;
   samples = 0;
   config = al_load_config_file("ex_stream_seek.cfg");
   if (config) {
      if ((s = al_get_config_value(config, "", "buffer_count"))) {
         buffer_count = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "samples"))) {
         samples = atoi(s);
      }
      if ((s = al_get_config_value(config, "", "playmode"))) {
         if (!strcmp(s, "loop")) {
            playmode = ALLEGRO_PLAYMODE_LOOP;
         }
         else if (!strcmp(s, "once")) {
            playmode = ALLEGRO_PLAYMODE_ONCE;
         }
      }
      al_destroy_config(config);
   }
   if (buffer_count == 0) {
      buffer_count = 4;
   }
   if (samples == 0) {
      samples = 1024;
   }

   music_stream = al_load_audio_stream(stream_filename, buffer_count, samples);
   if (!music_stream) {
      abort_example("Stream error!\n");
   }
   al_register_event_source(queue, al_get_audio_stream_event_source(music_stream));

   loop_start = 0.0;
   loop_end = al_get_audio_stream_length_secs(music_stream);
   al_set_audio_stream_loop_secs(music_stream, loop_start, loop_end);

   al_set_audio_stream_playmode(music_stream, playmode);
   al_attach_audio_stream_to_mixer(music_stream, al_get_default_mixer());
   al_start_timer(timer);

   while (!exiting) {
      al_wait_for_event(queue, &event);
      event_handler(&event);
   }

   myexit();
   al_destroy_display(display);
   close_log(true);
   return 0;
}
int main(int argc, char **argv)
{
   const char *filename = "../demos/cosmic_protector/data/sfx/title_music.ogg";
   ALLEGRO_VOICE *voice;
   ALLEGRO_MIXER *mixer;
   ALLEGRO_AUDIO_STREAM *stream;

   if (argc > 1) {
      filename = argv[1];
   }

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
      return 1;
   }

   al_init_primitives_addon();
   al_init_image_addon();
   al_init_acodec_addon();
   
   al_install_keyboard();

   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Could not create display.\n");
      return 1;
   }

   dbuf = al_create_bitmap(640, 480);

   bmp = al_load_bitmap("data/mysha.pcx");
   if (!bmp) {
      abort_example("Could not load data/mysha.pcx\n");
      return 1;
   }

   if (!al_install_audio()) {
      abort_example("Could not init sound.\n");
      return 1;
   }

   voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16,
      ALLEGRO_CHANNEL_CONF_2);
   if (!voice) {
      abort_example("Could not create voice.\n");
      return 1;
   }

   mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,
      ALLEGRO_CHANNEL_CONF_2);
   if (!mixer) {
      abort_example("Could not create mixer.\n");
      return 1;
   }

   if (!al_attach_mixer_to_voice(mixer, voice)) {
      abort_example("al_attach_mixer_to_voice failed.\n");
      return 1;
   }

   stream = al_load_audio_stream(filename, 4, 2048);
   if (!stream) {
      abort_example("Could not load '%s'\n", filename);
      return 1;
   }

   al_set_audio_stream_playmode(stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(stream, mixer);

   al_set_mixer_postprocess_callback(mixer, update_meter, NULL);

   main_loop();

   al_destroy_audio_stream(stream);
   al_destroy_mixer(mixer);
   al_destroy_voice(voice);
   al_uninstall_audio();

   al_destroy_bitmap(dbuf);
   al_destroy_bitmap(bmp);

   return 0;
}
static void mainloop(void)
{
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_TIMER *timer;
   float *buf;
   double pitch = 440;
   int i, si;
   int n = 0;
   bool redraw = false;
   
   for (i = 0; i < N; i++) {
      frequency[i] = 22050 * pow(2, i / (double)N);
      stream[i] = al_create_audio_stream(4, SAMPLES_PER_BUFFER, frequency[i],
         ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_1);
      if (!stream[i]) {
         abort_example("Could not create stream.\n");
         return;
      }

      if (!al_attach_audio_stream_to_mixer(stream[i], al_get_default_mixer())) {
         abort_example("Could not attach stream to mixer.\n");
         return;
      }
   }

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   for (i = 0; i < N; i++) {
      al_register_event_source(queue,
         al_get_audio_stream_event_source(stream[i]));
   }
#ifdef ALLEGRO_POPUP_EXAMPLES
   if (textlog) {
      al_register_event_source(queue, al_get_native_text_log_event_source(textlog));
   }
#endif

   log_printf("Generating %d sine waves of different sampling quality\n", N);
   log_printf("If Allegro's resampling is correct there should be little variation\n", N);

   timer = al_create_timer(1.0 / 60);
   al_register_event_source(queue, al_get_timer_event_source(timer));
   
   al_register_event_source(queue, al_get_display_event_source(display));

   al_start_timer(timer);
   while (n < 60 * frequency[0] / SAMPLES_PER_BUFFER * N) {
      ALLEGRO_EVENT event;

      al_wait_for_event(queue, &event);

      if (event.type == ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT) {
         for (si = 0; si < N; si++) {
            buf = al_get_audio_stream_fragment(stream[si]);
            if (!buf) {
               continue;
            }

            for (i = 0; i < SAMPLES_PER_BUFFER; i++) {
               double t = samplepos[si]++ / (double)frequency[si];
               buf[i] = sin(t * pitch * ALLEGRO_PI * 2) / N;
            }

            if (!al_set_audio_stream_fragment(stream[si], buf)) {
               log_printf("Error setting stream fragment.\n");
            }

            n++;
            log_printf("%d", si);
            if ((n % 60) == 0)
               log_printf("\n");
         }
      }
      
      if (event.type == ALLEGRO_EVENT_TIMER) {
         redraw = true;
      }

      if (event.type == ALLEGRO_EVENT_KEY_DOWN &&
            event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
         break;
      }

      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }

#ifdef ALLEGRO_POPUP_EXAMPLES
      if (event.type == ALLEGRO_EVENT_NATIVE_DIALOG_CLOSE) {
         break;
      }
#endif

      if (redraw &&al_is_event_queue_empty(queue)) {
         ALLEGRO_COLOR c = al_map_rgb(0, 0, 0);
         int i;
         al_clear_to_color(al_map_rgb_f(1, 1, 1));
        
         for (i = 0; i < 640; i++) {
            al_draw_pixel(i, 50 + waveform[i] * 50, c);
         }

         al_flip_display();
         redraw = false;
      }
   }

   for (si = 0; si < N; si++) {
      al_drain_audio_stream(stream[si]);
   }

   log_printf("\n");

   al_destroy_event_queue(queue);
}
Example #28
0
int main(int argc, char *argv[])
{
   ALLEGRO_DISPLAY *display;
   (void)argc;
   (void)argv;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }

   open_log();

   al_install_keyboard();
   al_install_mouse();

   al_init_primitives_addon();
   al_init_font_addon();
   al_init_ttf_addon();

   al_set_new_display_flags(ALLEGRO_GENERATE_EXPOSE_EVENTS);
   display = al_create_display(800, 600);
   if (!display) {
      abort_example("Unable to create display\n");
   }
   al_set_window_title(display, "Synthesiser of sorts");

   font_gui = al_load_ttf_font("data/DejaVuSans.ttf", 12, 0);
   if (!font_gui) {
      abort_example("Failed to load data/fixed_font.tga\n");
   }

   if (!al_install_audio()) {
      abort_example("Could not init sound!\n");
   }

   if (!al_reserve_samples(0)) {
      abort_example("Could not set up voice and mixer.\n");
   }

   size_t buffers = 8;
   unsigned samples = SAMPLES_PER_BUFFER;
   unsigned freq = STREAM_FREQUENCY;
   ALLEGRO_AUDIO_DEPTH depth = ALLEGRO_AUDIO_DEPTH_FLOAT32;
   ALLEGRO_CHANNEL_CONF ch = ALLEGRO_CHANNEL_CONF_1;

   stream1 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream2 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream3 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream4 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream5 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   if (!stream1 || !stream2 || !stream3 || !stream4 || !stream5) {
      abort_example("Could not create stream.\n");
   }

   ALLEGRO_MIXER *mixer = al_get_default_mixer();
   if (
      !al_attach_audio_stream_to_mixer(stream1, mixer) ||
      !al_attach_audio_stream_to_mixer(stream2, mixer) ||
      !al_attach_audio_stream_to_mixer(stream3, mixer) ||
      !al_attach_audio_stream_to_mixer(stream4, mixer) ||
      !al_attach_audio_stream_to_mixer(stream5, mixer)
   ) {
      abort_example("Could not attach stream to mixer.\n");
   }

   al_set_mixer_postprocess_callback(mixer, mixer_pp_callback, mixer);

   /* Prog is destroyed at the end of this scope. */
   {
      Theme theme(font_gui);
      Prog prog(theme, display);
      prog.run();
   }

   al_destroy_audio_stream(stream1);
   al_destroy_audio_stream(stream2);
   al_destroy_audio_stream(stream3);
   al_destroy_audio_stream(stream4);
   al_destroy_audio_stream(stream5);
   al_uninstall_audio();

   al_destroy_font(font_gui);

   al_fclose(save_fp);

   close_log(false);

   return 0;
}