Method: NuWav::WaveFile#parse

Defined in:
lib/nu_wav/wave_file.rb

#parse(wave_file) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/nu_wav/wave_file.rb', line 15

def parse(wave_file)
  NuWav::WaveFile.log "Processing wave file #{wave_file.inspect}...."
  wave_file_size = File.size(wave_file)

  File.open(wave_file, 'r') do |f|

    #only for windows, make sure we are operating in binary mode 
    f.binmode
    #start at the very beginning, a very good place to start
    f.seek(0)

    riff, riff_length = read_chunk_header(f)
    NuWav::WaveFile.log "riff: #{riff}"
    NuWav::WaveFile.log "riff_length: #{riff_length}"
    NuWav::WaveFile.log "wave_file_size: #{wave_file_size}"

    raise NotRIFFFormat unless riff == 'RIFF' || riff == 'RF64'
    riff_end = [f.tell + riff_length, wave_file_size].min

    riff_type = f.read(4)
    raise NotWAVEFormat unless riff_type == 'WAVE'

    @header = RiffChunk.new(riff, riff_length, riff_type)

    while (f.tell + 8) <= riff_end
      NuWav::WaveFile.log "while #{f.tell} < #{riff_end}"
      chunk_name, chunk_length = read_chunk_header(f)
      fpos = f.tell

      NuWav::WaveFile.log "found chunk: '#{chunk_name}', size #{chunk_length}"
      
      if chunk_name && chunk_length

        self.chunks[chunk_name.to_sym] = chunk_class(chunk_name).parse(chunk_name, chunk_length, f)
        parsed_chunk_size = self.chunks[chunk_name.to_sym].size

        NuWav::WaveFile.log "about to do a seek..."
        NuWav::WaveFile.log "f.seek #{fpos} + #{parsed_chunk_size}"
        f.seek(fpos + parsed_chunk_size)
        NuWav::WaveFile.log "seek done"

        if parsed_chunk_size.odd?
          NuWav::WaveFile.log("parsed_chunk_size is ODD #{chunk_name}: #{parsed_chunk_size}")
          pad = f.read(1)
          if (pad.nil? || pad.ord != 0)
            NuWav::WaveFile.log("NOT PADDED")
            self.chunks[chunk_name.to_sym].pad_byte = false
            f.seek(fpos + parsed_chunk_size)
          else
            self.chunks[chunk_name.to_sym].pad_byte = true
          end
        end

      else
        NuWav::WaveFile.log "chunk or length was off - remainder of file does not parse properly: #{riff_end} - #{fpos} = #{riff_end - fpos}"
        f.seek(riff_end)
      end
    end
  end
  @chunks.each{|k,v| NuWav::WaveFile.log "#{k}: #{v}\n\n" unless k.to_s == 'data'}
  NuWav::WaveFile.log "parse done"
  self
end