Class: AlsaBackup::Recorder

Inherits:
Object
  • Object
show all
Defined in:
lib/alsa_backup/recorder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = "record.wav") ⇒ Recorder

Returns a new instance of Recorder.



9
10
11
12
# File 'lib/alsa_backup/recorder.rb', line 9

def initialize(file = "record.wav")
  @file = file
  @directory = "."
end

Instance Attribute Details

#directoryObject

Returns the value of attribute directory.



14
15
16
# File 'lib/alsa_backup/recorder.rb', line 14

def directory
  @directory
end

#fileObject

Returns the value of attribute file.



14
15
16
# File 'lib/alsa_backup/recorder.rb', line 14

def file
  @file
end

Instance Method Details

#format(additional_parameters = {}) ⇒ Object



52
53
54
# File 'lib/alsa_backup/recorder.rb', line 52

def format(additional_parameters = {})
  {:sample_rate => 44100, :channels => 2}.merge(additional_parameters)
end

#sndfileObject



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/alsa_backup/recorder.rb', line 56

def sndfile
  target_file = self.target_file
  raise "no recording file" unless target_file

  unless @sndfile and @sndfile.path == target_file
    @sndfile.close if @sndfile
    AlsaBackup.logger.info "new file #{target_file}"

    FileUtils.mkdir_p File.dirname(target_file)
    @sndfile = Sndfile::File.new(target_file, "w", self.format(:format => "wav pcm_16"))
  end
  @sndfile
end

#start(seconds_to_record = nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/alsa_backup/recorder.rb', line 16

def start(seconds_to_record = nil)
  frames_to_record = format[:sample_rate] * seconds_to_record if seconds_to_record

  # prepare sndfile
  self.sndfile

  ALSA::PCM::Capture.open("hw:0", self.format(:sample_format => :s16_le)) do |capture|
    capture.read do |buffer, frame_count|
      self.sndfile.write buffer, frame_count
      if frames_to_record
        (frames_to_record -= frame_count) > 0
      else
        true
      end
    end
  end
rescue Exception => e
  AlsaBackup.logger.error(e)
  raise e
ensure
  @sndfile.close if @sndfile
end

#target_fileObject



48
49
50
# File 'lib/alsa_backup/recorder.rb', line 48

def target_file
  File.join self.directory, self.file
end