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()
22 alDeleteBuffers(STREAMFRAGMENTS, buffers);
23 SoundManager::check_al_error("Couldn't delete audio buffers: ");
27 StreamSoundSource::set_sound_file(SoundFile* newfile)
33 alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
34 for(size_t i = 0; i < STREAMFRAGMENTS - queued; ++i) {
35 if(fillBufferAndQueue(buffers[i]) == false)
41 StreamSoundSource::update()
44 alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
45 for(ALint i = 0; i < processed; ++i) {
47 alSourceUnqueueBuffers(source, 1, &buffer);
48 SoundManager::check_al_error("Couldn't unqueu audio buffer: ");
50 if(fillBufferAndQueue(buffer) == false)
55 if(processed == 0 || !looping)
58 // we might have to restart the source if we had a buffer underrun
59 log_info << "Restarting audio source because of buffer underrun" << std::endl;
63 if(fade_state == FadingOn) {
64 Uint32 ticks = SDL_GetTicks();
65 float time = (ticks - fade_start_ticks) / 1000.0;
66 if(time >= fade_time) {
68 fade_state = NoFading;
70 set_gain(time / fade_time);
72 } else if(fade_state == FadingOff) {
73 Uint32 ticks = SDL_GetTicks();
74 float time = (ticks - fade_start_ticks) / 1000.0;
75 if(time >= fade_time) {
77 fade_state = NoFading;
79 set_gain( (fade_time-time) / fade_time);
85 StreamSoundSource::set_fading(FadeState state, float fade_time)
87 this->fade_state = state;
88 this->fade_time = fade_time;
89 this->fade_start_ticks = SDL_GetTicks();
93 StreamSoundSource::fillBufferAndQueue(ALuint buffer)
96 char* bufferdata = new char[STREAMFRAGMENTSIZE];
99 bytesread += file->read(bufferdata + bytesread,
100 STREAMFRAGMENTSIZE - bytesread);
102 if(bytesread < STREAMFRAGMENTSIZE) {
108 } while(bytesread < STREAMFRAGMENTSIZE);
111 ALenum format = SoundManager::get_sample_format(file);
112 alBufferData(buffer, format, bufferdata, bytesread, file->rate);
114 SoundManager::check_al_error("Couldn't refill audio buffer: ");
116 alSourceQueueBuffers(source, 1, &buffer);
117 SoundManager::check_al_error("Couldn't queue audio buffer: ");
120 // return false if there aren't more buffers to fill
121 return bytesread >= STREAMFRAGMENTSIZE;