class STFTSpectrogram::AudioFile

Represents wave file

Constants

SAMPLE_RATE

Attributes

window_overlap[R]
window_size[R]

Public Class Methods

new(path, wsize = 1, woverlap = 0) click to toggle source
# File lib/audio/audio_file.rb, line 13
def initialize(path, wsize = 1, woverlap = 0)
  unless File.file?(path)
    raise IOError, "File '" + path + "' does not exist!"
  end
  @samples = []
  self.window_size = wsize
  self.window_overlap = woverlap
  @window_overlap = @window_size / 2 if @window_size <= @window_overlap
  @window_pos = 0
  read_data(path)
end
sample_rate() click to toggle source
# File lib/audio/audio_file.rb, line 58
def self.sample_rate
  SAMPLE_RATE
end

Public Instance Methods

current_time() click to toggle source

Gets the time corresponding to the window pointers location

# File lib/audio/audio_file.rb, line 68
def current_time
  (@window_pos + @window_size / 2) / (SAMPLE_RATE / 1000)
end
end?() click to toggle source

Checks if the window pointer is at the end of the file

# File lib/audio/audio_file.rb, line 73
def end?
  @window_pos + @window_size >= @samples.length
end
next_window() click to toggle source

Gets window_size of data from audio samples and moves the window pointer

# File lib/audio/audio_file.rb, line 48
def next_window
  return [] if end?

  slice = @samples[@window_pos, @window_size]
  slice.fill(0, slice.length..@window_size - 1)
  @window_pos += @window_size - @window_overlap

  slice
end
reset() click to toggle source

Resets the window pointer

# File lib/audio/audio_file.rb, line 63
def reset
  @window_pos = 0
end
window_overlap=(overlap) click to toggle source
# File lib/audio/audio_file.rb, line 38
def window_overlap=(overlap)
  @window_overlap = nearest_pow2(overlap * (SAMPLE_RATE / 1000))
end
window_size=(size) click to toggle source
# File lib/audio/audio_file.rb, line 42
def window_size=(size)
  @window_size = nearest_pow2(size * (SAMPLE_RATE / 1000))
end

Private Instance Methods

nearest_pow2(num) click to toggle source

Nearest power of 2 to num

# File lib/audio/audio_file.rb, line 33
def nearest_pow2(num)
  return 0 if num <= 0
  2**Math.log2(num).round
end
read_data(path) click to toggle source
# File lib/audio/audio_file.rb, line 25
def read_data(path)
  format = Format.new(:mono, :float, SAMPLE_RATE)
  Reader.new(path, format).each_buffer do |buffer|
    buffer.samples.each { |s| @samples.push(s) }
  end
end