Skip to content

Instantly share code, notes, and snippets.

@qoobaa
Created February 21, 2022 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qoobaa/6546a9ae29b234146a669e6d1fcce409 to your computer and use it in GitHub Desktop.
Save qoobaa/6546a9ae29b234146a669e6d1fcce409 to your computer and use it in GitHub Desktop.
require 'json'
require 'open-uri'
require 'open3'
STREAMS_URL = 'https://mixlr-codetest.herokuapp.com/stations/netil-radio/streams'
def fetch_streams(url = STREAMS_URL)
body = URI.open(url).read
json = JSON.parse(body)
json.dig('data', 'attributes', 'streams')
end
def analyze_stream_volume(stream_url)
# ffmpeg outputs all the relevant information to stderr, nothing
# interesting on stdout
_, stderr, process_info = Open3.capture3('ffmpeg', '-t', '3', '-i', stream_url, '-af', 'volumedetect', '-f', 'null', '/dev/null')
mean_volume = stderr.match(/mean_volume: (.*) dB/)[1].to_f
max_volume = stderr.match(/max_volume: (.*) dB/)[1].to_f
{mean_volume:, max_volume:}
end
def run!
fetch_streams.each do |stream_name, stream_url|
volumes = analyze_stream_volume(stream_url)
puts "#{stream_name} - mean volume: #{volumes[:mean_volume]} dB, max volume: #{volumes[:max_volume]} dB"
end
end
# do not run the script if it's been required by other scripts
run! if __FILE__ == $0
require 'rubygems'
require 'bundler/setup'
require 'webmock/minitest'
require 'minitest/autorun'
require_relative '../volume'
class VolumeTest < Minitest::Test
def test_fetch_streams_works_properly
body = {
data: {
attributes: {
streams: {
first: "first_stream_url",
second: "second_stream_url"
}
}
}
}
stub_request(:get, 'https://mixlr-codetest.herokuapp.com/stations/netil-radio/streams')
.to_return(body: JSON.generate(body))
streams = fetch_streams
assert_equal 2, streams.size
assert_equal "first_stream_url", streams["first"]
assert_equal "second_stream_url", streams["second"]
end
def test_analyze_stream_volume_works_properly
volumes = analyze_stream_volume('test/fixtures/test.mp3')
assert_equal -23.1, volumes[:mean_volume]
assert_equal -7.2, volumes[:max_volume]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment