Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require_relative 'lib/portaudio'
class AudioTest
include PortAudio
def initialize
PortAudio.init
@devices = get_devices
end
def run!
@devices.each do |device|
# 440Hz baby!
play(device)
end
end
def play(device)
if device.max_output_channels < 1
return false
end
puts "Playing on device: #{device.name} [#{device.max_output_channels}]"
frames = 1024
channels = 1
sr = 44100
step = 1.0/sr
time = 0.0
stream = PortAudio::Stream.open(
:sample_rate => sr,
:frames => frames,
:output => {
# :device => PortAudio::Device.default_output,
:device => device,
:channels => channels,
:sample_format => :float32,
:suggested_latency => 0.05
})
buffer = PortAudio::SampleBuffer.new(
:format => :float32,
:channels => channels,
:frames => frames)
playing = true
Signal.trap('INT') { playing = false }
puts "Ctrl-C for next"
stream.start
loop do
stream << buffer.fill { |frame, channel|
time += step
Math.cos(time * 2 * Math::PI * 440.0) * Math.cos(time * 2 * Math::PI)
}
break unless playing
end
stream.stop
end
def get_devices
device_count = Device.count - 1
devices = (0..device_count).map do |index|
Device.new(index)
end
end
end
if __FILE__ == $0
AudioTest.new.run!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment