4 #include "stream_sound_source.hpp"
5 #include "sound_manager.hpp"
6 #include "sound_file.hpp"
8 StreamSoundSource::StreamSoundSource()
9 : file(0), fade_state(NoFading)
11 alGenBuffers(STREAMFRAGMENTS, buffers);
12 SoundManager::check_al_error("Couldn't allocate audio buffers: ");
15 StreamSoundSource::~StreamSoundSource()
18 alDeleteBuffers(STREAMFRAGMENTS, buffers);
19 SoundManager::check_al_error("Couldn't delete audio buffers: ");
23 StreamSoundSource::set_sound_file(SoundFile* newfile)
29 alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
30 for(size_t i = 0; i < STREAMFRAGMENTS - queued; ++i) {
31 fillBufferAndQueue(buffers[i]);
36 StreamSoundSource::update()
39 alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
40 for(ALint i = 0; i < processed; ++i) {
42 alSourceUnqueueBuffers(source, 1, &buffer);
43 SoundManager::check_al_error("Couldn't unqueu audio buffer: ");
45 fillBufferAndQueue(buffer);
52 // we might have to restart the source if we had a buffer underrun
53 std::cerr << "Restarting audio source because of buffer underrun.\n";
59 alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
60 assert(queued == (ALint) STREAMFRAGMENTS);
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);
101 if(bytesread < STREAMFRAGMENTSIZE) {
104 } while(bytesread < STREAMFRAGMENTSIZE);
106 ALenum format = SoundManager::get_sample_format(file);
107 alBufferData(buffer, format, bufferdata, STREAMFRAGMENTSIZE, file->rate);
109 SoundManager::check_al_error("Couldn't refill audio buffer: ");
111 alSourceQueueBuffers(source, 1, &buffer);
112 SoundManager::check_al_error("Couldn't queue audio buffer: ");