Created
March 11, 2012 03:53
-
-
Save tehprofessor/2014924 to your computer and use it in GitHub Desktop.
Archiving Audio Stream in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
url = URI.parse('http://stream.kpsu.org:8080/listen') | |
# This thread is used to kill the recording thread after the | |
# designated amount of time. | |
timelimit = Thread.new do | |
# running_time_in_seconds is how many seconds the clip should be | |
# one hour = 3600 seconds | |
running_time_in_seconds = 60 | |
sleep(running_time_in_seconds) | |
# The last thread is the stream ripping thread, and we want to kill it | |
# after the specified amount of time | |
Thread.kill(Thread.list.last) | |
end | |
# This thread is what actually writes the file to disk, | |
# without the timelimit it will run forever until the stream | |
# breaks. | |
streamripper = Thread.new do | |
Net::HTTP.start(url.host, url.port) do |http| | |
# f is the file | |
# Time.now.to_i is an integer representation of time | |
# The file saves to the same directory the script is run from | |
# make sure it was write permission! | |
# if the format of the stream changes | |
f = open("#{Time.now.to_i}.mp3", "w") | |
begin | |
http.request_get('/') do |resp| | |
resp.read_body do |segment| | |
f.write(segment) | |
end | |
end | |
ensure | |
f.close() | |
end | |
end | |
end | |
# Put the threads in an array, I think it makes | |
# running them cleaner | |
threads=[timelimit, streamripper] | |
# Run the threads | |
threads.each{|t| t.join } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment