Class: Sf2ToJs

Inherits:
Object
  • Object
show all
Includes:
FileUtils
Defined in:
lib/sf2_to_js.rb

Constant Summary collapse

MIDI_LOWEST_NOTE_INDEX =
21
MIDI_HIGHTEST_NOTE_INDEX =
108
NOTES =
MIDI_LOWEST_NOTE_INDEX..MIDI_HIGHTEST_NOTE_INDEX
JS_NOTE_DURATION =

ms

2500
JS_NOTE_VELOCITY =
85

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sf2_path = nil, instrument_ids = [], output_dir = "./soundfonts/") ⇒ Sf2ToJs

Returns a new instance of Sf2ToJs.



17
18
19
20
21
22
23
# File 'lib/sf2_to_js.rb', line 17

def initialize sf2_path=nil, instrument_ids = [], output_dir="./soundfonts/"
  check_deps
  @sf2_path = File.expand_path(sf2_path)
  @instrument_ids = instrument_ids
  @output_dir = File.expand_path(output_dir)
  mkdir_p @output_dir
end

Instance Attribute Details

#instrument_idsObject

Returns the value of attribute instrument_ids.



15
16
17
# File 'lib/sf2_to_js.rb', line 15

def instrument_ids
  @instrument_ids
end

#output_dirObject

Returns the value of attribute output_dir.



15
16
17
# File 'lib/sf2_to_js.rb', line 15

def output_dir
  @output_dir
end

#sf2_pathObject

Returns the value of attribute sf2_path.



15
16
17
# File 'lib/sf2_to_js.rb', line 15

def sf2_path
  @sf2_path
end

Instance Method Details

#check_depsObject



25
26
27
28
# File 'lib/sf2_to_js.rb', line 25

def check_deps
  raise 'missing fluidsynth (brew install fluidsynth)' unless `which fluidsynth`
  raise 'missing oggenc (brew install fluidsynth)' unless `which oggenc`
end

#to_jsObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/sf2_to_js.rb', line 30

def to_js
  raise 'no sf2_path!' unless File.exist? @sf2_path

  font_root_name = File.basename @sf2_path, '.*'
  path = "window.Midi.Soundfont.#{font_root_name}"

  instruments.each do |inst|
    inst_root_name = inst[:name].gsub(/\s*/, "")
    @js_file = File.open("#{@output_dir}/#{font_root_name}.#{inst_root_name}.sf2.js", "w")
    @js_file.puts define_js(path)

    @js_file.puts "#{path}[\"#{inst[:name]}\"] = ["
    NOTES.each do |note_index|
      ogg_64b = ogg_64b_note(inst[:bank], inst[:id], note_index)
      @js_file.print "  \"#{ogg_64b}\""
      @js_file.puts ", " unless (note_index == MIDI_HIGHTEST_NOTE_INDEX)
    end
    @js_file.puts
    @js_file.print "];"

    @js_file.close
  end
end