Skip to content

Instantly share code, notes, and snippets.

@Sixeight
Forked from hitode909/olm.rb
Created October 22, 2011 02:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sixeight/1305432 to your computer and use it in GitHub Desktop.
Save Sixeight/1305432 to your computer and use it in GitHub Desktop.
One liner music player for Ruby. http://hitode909.appspot.com/one-liner-music/
require 'rubygems'
require 'ffi-portaudio'
def safe
r = nil
Thread.new {
$SAFE = 4
r = yield
}.join
r
end
class OLMStream < FFI::PortAudio::Stream
attr_accessor :generator
def initialize
@count = 0
@max = 1
end
def process(input, output, frameCount, timeInfo, statusFlags, userData)
wave = (0...frameCount).map{|i|@generator.call(@count+=1) % 255}
@max = [wave.max, @max].max
volume = 0x8000.quo @max
output.write_array_of_int16 wave.map!{|v| v * volume}
:paContinue
end
end
include FFI::PortAudio
def create_music(generator)
fork do
API.Pa_Initialize
output = API::PaStreamParameters.new
output[:device] = API.Pa_GetDefaultOutputDevice
output[:channelCount] = 1
output[:sampleFormat] = API::Int16
output[:suggestedLatency] = 0.2
output[:hostApiSpecificStreamInfo] = nil
s = OLMStream.new
s.generator = safe { eval "lambda {|t| #{generator} }" }
s.open(nil, output, 8000)
s.start
at_exit do
s.close
API.Pa_Terminate
end
loop { sleep 1 }
end
end
ARGV.each do |generator|
create_music(generator)
end
loop { sleep 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment