Class: Hanvox::ProcAudio

Inherits:
Object
  • Object
show all
Defined in:
lib/hanvox/proc_audio.rb

Constant Summary collapse

CHUNK_IDS =
{:header       => "RIFF",
:format       => "fmt ",
:data         => "data",
:fact         => "fact",
:silence      => "slnt",
:cue          => "cue ",
:playlist     => "plst",
:list         => "list",
:label        => "labl",
:labeled_text => "ltxt",
:note         => "note",
:sample       => "smpl",
:instrument   => "inst" }
PACK_CODES =
{8 => "C*", 16 => "s*", 32 => "V*"}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, save_dir = nil) ⇒ ProcAudio

Returns a new instance of ProcAudio.



23
24
25
26
27
28
29
30
31
32
# File 'lib/hanvox/proc_audio.rb', line 23

def initialize path, save_dir=nil
  @channels, @data, @results = [], [], []
  @header = {}
  @save_dir = save_dir || `pwd`.gsub("\n", "")
  @path = path

  @file = File.open path
  @oname = File.basename path, ".wav"
  read_header
end

Instance Attribute Details

#channelsObject

Returns the value of attribute channels.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def channels
  @channels
end

#dataObject

Returns the value of attribute data.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def data
  @data
end

#fileObject

Returns the value of attribute file.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def file
  @file
end

#headerObject

Returns the value of attribute header.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def header
  @header
end

#onameObject

Returns the value of attribute oname.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def oname
  @oname
end

#pathObject

Returns the value of attribute path.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def path
  @path
end

#processorsObject

Returns the value of attribute processors.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def processors
  @processors
end

#resultsObject

Returns the value of attribute results.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def results
  @results
end

#sample_countObject

Returns the value of attribute sample_count.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def sample_count
  @sample_count
end

#save_dirObject

Returns the value of attribute save_dir.



7
8
9
# File 'lib/hanvox/proc_audio.rb', line 7

def save_dir
  @save_dir
end

Instance Method Details

#cleanupObject



191
192
193
194
195
196
197
198
# File 'lib/hanvox/proc_audio.rb', line 191

def cleanup
  @channels.each do |c|
    system "rm -f #{c}"
  end
  @file.close

  true
end

#process(opts = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/hanvox/proc_audio.rb', line 34

def process opts={}
  (@header[:channels]).times do |c|
    c += 1
    system "sox #{@path} -s #{oname}_#{c}.wav remix #{c}"
    system "sox #{oname}_#{c}.wav -s #{oname}_#{c}.raw"
    system "rm -f #{oname}_#{c}.wav"
    @channels << "#{oname}_#{c}.raw"
  end

  if opts[:channel].nil?
    @channels.each do |chan|
      process_audio chan
    end
  else
    process_audio @channels[opts[:channel]-1]
  end
  cleanup
end

#process_audio(input) ⇒ Object



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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/hanvox/proc_audio.rb', line 53

def process_audio input
  bname = File.expand_path(File.dirname(input))
  num   = File.basename(input, ".raw").split("_").last
  res   = {}

  #
  # Create the signature database
  #
  raw  = Hanvox::Raw.from_file(input)
  fft  = KissFFT.fftr(8192, 8000, 1, raw.samples)

  freq = raw.to_freq_sig_txt()

  # Save the signature data
  res[:fprint] = freq

  #
  # Create a raw decompressed file
  #

  # Decompress the audio file
  datfile = Tempfile.new("datfile")

  # Data files for audio processing and signal graph
  cnt = 0
  datfile.write(raw.samples.map{|val| cnt +=1; "#{cnt/8000.0} #{val}"}.join("\n"))
  datfile.flush

  # Data files for spectrum plotting
  frefile = Tempfile.new("frefile")

  # Calculate the peak frequencies for the sample
  maxf = 0
  maxp = 0
  tones = {}
  fft.each do |x|
    rank = x.sort{|a,b| a[1].to_i <=> b[1].to_i }.reverse
    rank[0..10].each do |t|
      f = t[0].round
      p = t[1].round
      next if f == 0
      next if p < 1
      tones[ f ] ||= []
      tones[ f ] << t
      if(t[1] > maxp)
        maxf = t[0]
        maxp = t[1]
      end
    end
  end

  # Save the peak frequency
  res[:peak_freq] = maxf

  # Calculate average frequency and peaks over time
  avg = {}
  pks = []
  pkz = []
  fft.each do |slot|
    pks << slot.sort{|a,b| a[1] <=> b[1] }.reverse[0]
    pkz << slot.sort{|a,b| a[1] <=> b[1] }.reverse[0..9]
    slot.each do |f|
      avg[ f[0] ] ||= 0
      avg[ f[0] ] +=  f[1]
    end
  end

  # Save the peak frequencies over time
  res[:peak_freq_data] = pks.map{|f| "#{f[0]}-#{f[1]}" }.join(" ")

  # Generate the frequency file
  avg.keys.sort.each do |k|
    avg[k] = avg[k] / fft.length
    frefile.write("#{k} #{avg[k]}\n")
  end
  frefile.flush

  # Count significant frequencies across the sample
  fcnt = {}
  0.step(4000, 5) {|f| fcnt[f] = 0 }
  pkz.each do |fb|
    fb.each do |f|
      fdx = ((f[0] / 5.0).round * 5.0).to_i
      fcnt[fdx]  += 0.1
    end
  end

  @data << { :raw  => raw, :freq => freq, :fcnt => fcnt, :fft  => fft,
            :pks  => pks, :pkz  => pkz, :maxf => maxf, :maxp => maxp }

  sigs = Signatures::Base.new @data.last
  res[:line_type] = sigs.process

  # Plot samples to a graph
  plotter = Tempfile.new("gnuplot")

  plotter.puts("set ylabel \"Signal\"")
  plotter.puts("set xlabel \"Seconds\"")
  plotter.puts("set terminal png medium size 640,480 transparent")
  plotter.puts("set output \"#{save_dir}/#{oname}_#{num}_big.png\"")
  plotter.puts("plot \"#{datfile.path}\" using 1:2 title \"#{num}\" with lines")
  plotter.puts("set output \"#{save_dir}/#{oname}_#{num}_big_dots.png\"")
  plotter.puts("plot \"#{datfile.path}\" using 1:2 title \"#{num}\" with dots")

  plotter.puts("set terminal png medium size 640,480 transparent")
  plotter.puts("set ylabel \"Power\"")
  plotter.puts("set xlabel \"Frequency\"")
  plotter.puts("set output \"#{save_dir}/#{oname}_#{num}_big_freq.png\"")
  plotter.puts("plot \"#{frefile.path}\" using 1:2 title \"#{num} - Peak #{maxf.round}hz\" with lines")

  plotter.puts("set ylabel \"Signal\"")
  plotter.puts("set xlabel \"Seconds\"")
  plotter.puts("set terminal png small size 160,120 transparent")
  plotter.puts("set format x ''")
  plotter.puts("set format y ''")
  plotter.puts("set output \"#{save_dir}/#{oname}_#{num}_sig.png\"")
  plotter.puts("plot \"#{datfile.path}\" using 1:2 notitle with lines")

  plotter.puts("set ylabel \"Power\"")
  plotter.puts("set xlabel \"Frequency\"")
  plotter.puts("set terminal png small size 160,120 transparent")
  plotter.puts("set format x ''")
  plotter.puts("set format y ''")
  plotter.puts("set output \"#{save_dir}/#{oname}_#{num}_sig_freq.png\"")
  plotter.puts("plot \"#{frefile.path}\" using 1:2 notitle with lines")
  plotter.flush

  puts `gnuplot #{plotter.path}&`
  File.unlink(plotter.path)
  File.unlink(datfile.path)
  File.unlink(frefile.path)
  plotter.close
  datfile.close
  frefile.path

  @results << res
end