6 #include "stream_sound_source.hpp"
7 #include "sound_manager.hpp"
8 #include "sound_file.hpp"
11 StreamSoundSource::StreamSoundSource()
12 : file(0), fade_state(NoFading), looping(false)
14 alGenBuffers(STREAMFRAGMENTS, buffers);
15 SoundManager::check_al_error("Couldn't allocate audio buffers: ");
18 StreamSoundSource::~StreamSoundSource()
21 alDeleteBuffers(STREAMFRAGMENTS, buffers);
22 SoundManager::check_al_error("Couldn't delete audio buffers: ");
26 StreamSoundSource::set_sound_file(SoundFile* newfile)
32 alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
33 for(size_t i = 0; i < STREAMFRAGMENTS - queued; ++i) {
34 if(fillBufferAndQueue(buffers[i]) == false)
40 StreamSoundSource::update()
43 alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
44 for(ALint i = 0; i < processed; ++i) {
46 alSourceUnqueueBuffers(source, 1, &buffer);
47 SoundManager::check_al_error("Couldn't unqueu audio buffer: ");
49 if(fillBufferAndQueue(buffer) == false)
54 if(processed == 0 || !looping)
57 // we might have to restart the source if we had a buffer underrun
58 msg_info("Restarting audio source because of buffer underrun");
62 if(fade_state == FadingOn) {
63 Uint32 ticks = SDL_GetTicks();
64 float time = (ticks - fade_start_ticks) / 1000.0;
65 if(time >= fade_time) {
67 fade_state = NoFading;
69 set_gain(time / fade_time);
71 } else if(fade_state == FadingOff) {
72 Uint32 ticks = SDL_GetTicks();
73 float time = (ticks - fade_start_ticks) / 1000.0;
74 if(time >= fade_time) {
76 fade_state = NoFading;
78 set_gain( (fade_time-time) / fade_time);
84 StreamSoundSource::set_fading(FadeState state, float fade_time)
86 this->fade_state = state;
87 this->fade_time = fade_time;
88 this->fade_start_ticks = SDL_GetTicks();
92 StreamSoundSource::fillBufferAndQueue(ALuint buffer)
95 char* bufferdata = new char[STREAMFRAGMENTSIZE];
98 bytesread += file->read(bufferdata + bytesread,
99 STREAMFRAGMENTSIZE - bytesread);
101 if(bytesread < STREAMFRAGMENTSIZE) {
107 } while(bytesread < STREAMFRAGMENTSIZE);
110 ALenum format = SoundManager::get_sample_format(file);
111 alBufferData(buffer, format, bufferdata, bytesread, file->rate);
113 SoundManager::check_al_error("Couldn't refill audio buffer: ");
115 alSourceQueueBuffers(source, 1, &buffer);
116 SoundManager::check_al_error("Couldn't queue audio buffer: ");
119 // return false if there aren't more buffers to fill
120 return bytesread >= STREAMFRAGMENTSIZE;