1/** Initializes the audio system
2 @return a pointer to an initialized Audio struct
3 */
4 Audio
* init_audio
()
5 {
6 if(! al_install_audio()){ perror_with_context
("Failed to install audio", __LINE__, __FILE__
); exit(EXIT_FAILURE
); }
7 else
8 {
9 if(! al_init_acodec_addon()) { perror_with_context
("Failed to initialize the codec addon", __LINE__, __FILE__
); exit(EXIT_FAILURE
); }
10 else
11 {
12 if(! al_reserve_samples(MAX_SAMPLES_NUMBER
)){ perror_with_context
("Failed to reserve channels", __LINE__, __FILE__
); exit(EXIT_FAILURE
); }
13 }
14 }
15
16 Audio
* audio
= (Audio
*) malloc(sizeof(Audio
));
17 audio->mixer
= al_get_default_mixer();
18 audio->stream
= NULL
;
19 audio->stream_loaded
= false;
20 if(! audio->mixer
)
21 { perror_with_context
("Failed to get the default mixer", __LINE__, __FILE__
); exit(EXIT_FAILURE
); }
22 return audio
;
23 }
24
25 /** Loads an audio stream
26 @param the path to the to-be-loaded audio stream
27 @param a pointer to an Audio struct
28 @return a boolean, indicating whether the audio stream was loaded or !
29 */
30 void load_audio_stream
(const char * stream_path,
ALLEGRO_EVENT_QUEUE * queue, Audio
* audio
)
31 {
32 audio->stream
= al_load_audio_stream(stream_path, MAX_BUFFER_NUMBER, MAX_STREAM_SAMPLES_NUMBER
);
33 if(! audio->stream
) { perror_with_context
("Failed to load the audio stream", __LINE__, __FILE__
); exit(EXIT_FAILURE
); }
34 else
35 {
36 al_register_event_source(queue,
al_get_audio_stream_event_source(audio->stream
));
37 if(! al_attach_audio_stream_to_mixer(audio->stream, audio->mixer
))
38 { perror_with_context
("Failed to attach the audio stream to the mixer", __LINE__, __FILE__
); exit(EXIT_FAILURE
); }
39 audio->stream_loaded
= true;
40 }
41 }
42
43 /** Streams audio
44 @param a pointer to an Audio struct
45 @param a pointer to an ALLEGRO_EVENT struct
46 */
47 void stream_audio
(Audio
* audio,
const ALLEGRO_EVENT * event
)
48 {
49 if(event->type
== ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT
)
50 {
51 void * stream_fragment
= al_get_audio_stream_fragment(audio->stream
);
52 al_set_audio_stream_fragment(audio->stream, stream_fragment
);
53 }
54 else if(event->type
== ALLEGRO_EVENT_AUDIO_STREAM_FINISHED
) { al_drain_audio_stream(audio->stream
); }
55 }
56
57 /** Terminates an audio stream
58 @param a pointer to an Audio struct
59 */
60 void end_audio_stream
(Audio
* audio
)
61 {
62 if(audio->stream
!= NULL
)
63 {
64 al_detach_audio_stream(audio->stream
);
65 al_destroy_audio_stream(audio->stream
);
66 }
67 }
68
69void run_event
(Game_event_queue
* game_event_queue, Levels
* levels, Videos
* videos, Audio
* audio,
ALLEGRO_EVENT_QUEUE * queue,
ALLEGRO_EVENT * event
)
70 {
71 if(event->type
== ALLEGRO_EVENT_TIMER
)
72 {
73 play_video
(game_event_queue, videos, audio, queue
);
74 }
75 else if((event->type
== ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT
) || (event->type
== ALLEGRO_EVENT_AUDIO_STREAM_FINISHED
)) { stream_audio
(audio, event
); }
76 }