Class: WinDSP

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

Defined Under Namespace

Modules: WinMM

Constant Summary collapse

VERSION =
"0.0.3"
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
54
55
56
57
# 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
  if /64/ =~ RUBY_PLATFORM
    @handle, = tmp.unpack("Q!")
  else
    @handle, = tmp.unpack("L!")
  end
  @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



59
60
61
62
63
64
65
66
67
# File 'lib/windsp.rb', line 59

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

#flushObject



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/windsp.rb', line 81

def flush
  if /64/ =~ RUBY_PLATFORM
    x = "Q!"
  else
    x = "L!"
  end
  hdr = [@buffer, @buffer.bytesize, 0, 0, 0, 0, nil, 0].pack("pVV#{x}VVp#{x}")
  @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



109
110
111
# File 'lib/windsp.rb', line 109

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

#wait(hdr) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/windsp.rb', line 69

def wait(hdr)
  if /64/ =~ RUBY_PLATFORM
    x = "Q!"
  else
    x = "L!"
  end
  while true
    break if (hdr.unpack("pVV#{x}VVp#{x}")[4] & WinMM::WHDR_DONE) == WinMM::WHDR_DONE
    sleep 0
  end
end

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



104
105
106
107
# File 'lib/windsp.rb', line 104

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