Class: ALSA::PCM::Capture

Inherits:
Stream
  • Object
show all
Defined in:
lib/alsa/pcm/capture.rb

Instance Attribute Summary

Attributes inherited from Stream

#handle

Instance Method Summary collapse

Methods inherited from Stream

#change_hardware_parameters, #check_handle!, #close, #hardware_parameters, #hardware_parameters=, #open, open, #opened?

Instance Method Details

#native_constantObject



4
5
6
# File 'lib/alsa/pcm/capture.rb', line 4

def native_constant
  ALSA::PCM::Native::STREAM_CAPTURE
end

#readObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/alsa/pcm/capture.rb', line 8

def read
  check_handle!

  ALSA.logger.debug { "start read with #{hw_params.sample_rate}, #{hw_params.channels} channels"}

  # use an 500ms buffer
  frame_count = hw_params.sample_rate / 2
  ALSA.logger.debug { "allocate #{hw_params.buffer_size_for(frame_count)} bytes for #{frame_count} frames" }
  FFI::MemoryPointer.new(:char, hw_params.buffer_size_for(frame_count)) do |buffer|
    begin
      read_buffer buffer, frame_count
    end while yield buffer, frame_count
  end
end

#read_buffer(buffer, frame_count) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/alsa/pcm/capture.rb', line 23

def read_buffer(buffer, frame_count)
  check_handle!

  read_count = ALSA::try_to "read from audio interface" do
    response = ALSA::PCM::Native::readi(self.handle, buffer, frame_count)
    if ALSA::Native::error_code?(response)
      ALSA.logger.warn { "try to recover '#{ALSA::Native::strerror(response)}' on read"}
      ALSA::PCM::Native::pcm_recover(self.handle, response, 1)
    else
      response
    end
  end

  missing_frame_count = frame_count - read_count
  if missing_frame_count > 0
    ALSA.logger.debug { "re-read missing frame count: #{missing_frame_count}"}
    read_buffer_size = hw_params.buffer_size_for(read_count)
    # buffer[read_buffer_size] doesn't return a MemoryPointer
    read_buffer(buffer + read_buffer_size, missing_frame_count)
  end
end