diff --git a/samples/queue_audio.cr b/samples/queue_audio.cr new file mode 100644 index 0000000..1a22f7a --- /dev/null +++ b/samples/queue_audio.cr @@ -0,0 +1,40 @@ +require "../src/sdl" + +CHANNELS = 1 +BUFFER_SIZE = 4096 +SAMPLE_RATE = 44100 + +SDL.init(SDL::Init::AUDIO) +at_exit { SDL.quit } + +audiospec = LibSDL::AudioSpec.new +audiospec.freq = SAMPLE_RATE +audiospec.format = LibSDL::AUDIO_F32SYS +audiospec.channels = CHANNELS +audiospec.samples = BUFFER_SIZE +audiospec.callback = nil +audiospec.userdata = nil + +obtained_spec = LibSDL::AudioSpec.new + +raise "Failed to open audio" if LibSDL.open_audio(pointerof(audiospec), pointerof(obtained_spec)) > 0 + +LibSDL.pause_audio 0 + +amp = 0.25 +freq = 500 +time = 0.0 +delta_time = 1 / SAMPLE_RATE +buffer = Slice(Float32).new BUFFER_SIZE + +loop do + BUFFER_SIZE.times do |sample| # fill buffer with simple sine wave + value = amp * Math.sin(2 * Math::PI * freq * time) + buffer[sample] = value.to_f32 + time += delta_time + end + while LibSDL.get_queued_audio_size(1) > BUFFER_SIZE * sizeof(Float32) * 2 # delay until we need more buffered audio + LibSDL.delay(1) + end + LibSDL.queue_audio(1, buffer, BUFFER_SIZE * sizeof(Float32)) +end diff --git a/src/lib_sdl/audio.cr b/src/lib_sdl/audio.cr index 5256348..423d56c 100644 --- a/src/lib_sdl/audio.cr +++ b/src/lib_sdl/audio.cr @@ -116,4 +116,9 @@ lib LibSDL fun close_audio = SDL_CloseAudio fun close_audio = SDL_CloseAudioDevice(dev : AudioDeviceID) + + fun queue_audio = SDL_QueueAudio(dev : AudioDeviceID, data : Void*, len : UInt32) : Int + fun dequeue_audio = SDL_DequeueAudio(dev : AudioDeviceID, data : Void*, len : UInt32) : UInt32 + fun get_queued_audio_size = SDL_GetQueuedAudioSize(dev : AudioDeviceID) : UInt32 + fun clear_queued_audio = SDL_ClearQueuedAudio(dev : AudioDeviceID) end diff --git a/src/window.cr b/src/window.cr index d04f658..6aac1c5 100644 --- a/src/window.cr +++ b/src/window.cr @@ -5,20 +5,31 @@ module SDL alias Flags = LibSDL::WindowFlags alias Position = LibSDL::WindowPosition - getter width : Int32 - getter height : Int32 - - def initialize(title, @width, @height, + def initialize(title, width, height, x : Position = Position::UNDEFINED, y : Position = Position::UNDEFINED, flags : Flags = Flags::SHOWN) - @window = LibSDL.create_window(title, x, y, @width, @height, flags) + @window = LibSDL.create_window(title, x, y, width, height, flags) end def finalize LibSDL.destroy_window(self) end + # Get the window's current width and height + def size : Tuple(Int32, Int32) + LibSDL.get_window_size(@window, out w, out h) + {w, h} + end + + def width : Int32 + size[0] + end + + def height : Int32 + size[1] + end + def surface @surface ||= begin surface = LibSDL.get_window_surface(self) @@ -71,8 +82,8 @@ module SDL {% end %} enum Fullscreen - WINDOW = 0 - FULLSCREEN = LibSDL::WindowFlags::FULLSCREEN + WINDOW = 0 + FULLSCREEN = LibSDL::WindowFlags::FULLSCREEN FULLSCREEN_DESKTOP = LibSDL::WindowFlags::FULLSCREEN_DESKTOP end