Class: WaveFile::HeaderReader

Inherits:
Object
  • Object
show all
Defined in:
lib/wavefile/reader.rb

Overview

Used to read the RIFF chunks in a wave file up until the data chunk. Thus is can be used to open a wave file and “queue it up” to the start of the actual sample data, as well as extract information out of pre-data chunks, such as the format chunk.

Constant Summary collapse

RIFF_CHUNK_HEADER_SIZE =
12
FORMAT_CHUNK_MINIMUM_SIZE =
16

Instance Method Summary collapse

Constructor Details

#initialize(file, file_name) ⇒ HeaderReader

Returns a new instance of HeaderReader.



225
226
227
228
# File 'lib/wavefile/reader.rb', line 225

def initialize(file, file_name)
  @file = file
  @file_name = file_name
end

Instance Method Details

#read_until_data_chunkObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/wavefile/reader.rb', line 230

def read_until_data_chunk
  read_riff_chunk

  begin
    chunk_id = @file.sysread(4)
    chunk_size = @file.sysread(4).unpack(UNSIGNED_INT_32).first
    while chunk_id != CHUNK_IDS[:data]
      if chunk_id == CHUNK_IDS[:format]
        format_chunk = read_format_chunk(chunk_id, chunk_size)
      else
        # Other chunk types besides the format chunk are ignored. This may change in the future.
        @file.sysread(chunk_size)
      end

      chunk_id = @file.sysread(4)
      chunk_size = @file.sysread(4).unpack(UNSIGNED_INT_32).first
    end
  rescue EOFError
    raise_error InvalidFormatError, "It doesn't have a data chunk."
  end

  if format_chunk == nil
    raise_error InvalidFormatError, "The format chunk is either missing, or it comes after the data chunk."
  end

  sample_frame_count = chunk_size / format_chunk[:block_align]

  return format_chunk, sample_frame_count
end