Class: RazyK::Audio::Player

Inherits:
Object
  • Object
show all
Defined in:
lib/razyk/audio/player.rb

Instance Method Summary collapse

Constructor Details

#initialize(tempo: 4) ⇒ Player

Returns a new instance of Player.



8
9
10
11
12
13
14
15
16
17
# File 'lib/razyk/audio/player.rb', line 8

def initialize(tempo: 4)
  @tempo = tempo
  @dev = CoreAudio.default_output_device
  @buf = @dev.output_buffer(1024)
  @beat_samples = (@dev.nominal_rate / (@tempo * 4)).floor
  @beat_bufs = Hash.new { |h, k| h[k] = NArray.sint(@beat_samples * (k+1)) }
  @samples = 0
  @queue = Queue.new
  @thread = nil
end

Instance Method Details

#play(length, octave, note) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/razyk/audio/player.rb', line 19

def play(length, octave, note)
  unless (0..8).include?(octave)
    octave = 4
  end
  unless (0..11).include?(note)
    note = 0
  end
  @queue.push([length, octave, note])
  if @thread.nil? or not(@thread.status)
    @thread = Thread.start{ run }
  end
end

#runObject



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
# File 'lib/razyk/audio/player.rb', line 37

def run
  begin
    @buf.start
    while (tuple = @queue.pop)
      length, octave, note = tuple
      wav = @beat_bufs[length]
      if octave | note == 0
        wav.fill!(0)
      else
        freq = (440.0 * (2 ** (octave-4))) # An
        freq *= 2 ** ((note-9)/12.0)
        phase = Math::PI * 2 * freq / @dev.nominal_rate
        breath = (@beat_samples * 0.2).round
        eot = wav.size - breath
        eot.times do |j|
          wav[j] = (0.7 * Math.sin(phase*(@samples+j)) * 0x7FFF).round
        end
        breath.times do |j|
          wav[eot+j] = 0
        end
        @samples += wav.size
        @buf << wav
      end
    end
  rescue
    puts $!, $@
  ensure
    @buf.stop
  end
end

#stopObject



32
33
34
35
# File 'lib/razyk/audio/player.rb', line 32

def stop
  @queue.push(nil)
  @thread.join if @thread
end