Class: WinDSP

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

Defined Under Namespace

Modules: WinMM

Constant Summary collapse

VERSION =
"0.0.4"
CHANNELS =
1
BITS =
8
FREQUENCY =
8000
BUFFER_FLUSH_SEC =
4

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*rest) ⇒ WinDSP

Returns a new instance of WinDSP.



45
46
47
48
49
50
51
52
53
# File 'lib/windsp.rb', line 45

def initialize(*rest)
  tmp = "\0" * 8
  form = [WinMM::WAVE_FORMAT_PCM, CHANNELS, FREQUENCY, rate, (BITS / 8) * CHANNELS, BITS, 0].pack("vvVVvvv")
  ret = WinMM.waveOutOpen(tmp, 0, form, 0, 0, WinMM::WAVE_ALLOWSYNC | WinMM::WAVE_MAPPED)
  raise "cannot open wave device: #{ret}" if ret != 0
  @handle, = tmp.unpack(WinMM::PACK)
  @hdr = nil
  @buffer = ""
end

Class Method Details

.open(*rest, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/windsp.rb', line 28

def self.open(*rest, &block)
  io = self.new(rest)
  if block
    begin
      block.call(io)
    ensure
      io.close
    end
  else
    io
  end
end

Instance Method Details

#closeObject



55
56
57
58
59
60
61
62
63
# File 'lib/windsp.rb', line 55

def close
  flush
  if @hdr
    wait(@hdr)
    WinMM.waveOutUnprepareHeader(@handle, @hdr, @hdr.bytesize)
    @hdr = nil
  end
  WinMM.waveOutClose(@handle)
end

#flushObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/windsp.rb', line 72

def flush
  hdr = [@buffer, @buffer.bytesize, 0, 0, 0, 0, nil, 0].pack("pVV#{WinMM::PACK}VVp#{WinMM::PACK}")
  @buffer = ""
  ret = WinMM.waveOutPrepareHeader(@handle, hdr, hdr.bytesize)
  raise "error in waveOutPrepareHeader: #{ret}" if ret != 0
  if @hdr
    wait(@hdr)
    WinMM.waveOutUnprepareHeader(@handle, @hdr, @hdr.bytesize)
    @hdr = nil
  end
  ret = WinMM.waveOutWrite(@handle, hdr, hdr.bytesize)
  raise "error in waveOutWrite: #{ret}" if ret != 0
  @hdr = hdr

  self
end

#rateObject



95
96
97
# File 'lib/windsp.rb', line 95

def rate
  FREQUENCY * (BITS / 8) * CHANNELS
end

#wait(hdr) ⇒ Object



65
66
67
68
69
70
# File 'lib/windsp.rb', line 65

def wait(hdr)
  while true
    break if (hdr.unpack("pVV#{WinMM::PACK}VVp#{WinMM::PACK}")[4] & WinMM::WHDR_DONE) == WinMM::WHDR_DONE
    sleep 0
  end
end

#write(str) ⇒ Object Also known as: binwrite, print, syswrite, <<



90
91
92
93
# File 'lib/windsp.rb', line 90

def write(str)
  @buffer << str
  flush if @buffer.bytesize >= BUFFER_FLUSH_SEC * rate
end