Created
December 14, 2018 04:07
-
-
Save daviscodesbugs/857927d7a546b3e939a482e57c207462 to your computer and use it in GitHub Desktop.
Make Waves
This file contains 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
# http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html | |
# http://soundfile.sapp.org/doc/WaveFormat/ | |
filename = ARGV[0] | |
filesize = File.size(filename) | |
puts "Reading #{filename} (#{filesize} bytes)" | |
# Constant | |
chunkID = "RIFF" | |
format = "WAVE" | |
subchunk1ID = "fmt " | |
subchunk2ID = "data" | |
subchunk1Size = 16 # turn into byte representation (10 00 00 00) | |
# Set | |
data = File.read(filename).to_slice.to_a | |
sampleRate = 44100 # turn into 4-byte rep (44 ac 00 00) | |
bitsPerSample = 16 # turn into 2-byte rep (10 00) | |
numChannels = 2 # turn into 2-byte rep (02 00) | |
audioFormat = 1 # turn into 2-byte representation (01 00) | |
# Calculated | |
subchunk2Size = filesize # Turn into a bytes representation | |
chunkSize = 36 + subchunk2Size | |
byteRate = sampleRate * numChannels * (bitsPerSample / 8) | |
blockAlign = numChannels * (bitsPerSample / 8) | |
combined = chunkID.bytes | |
combined += toBytes(chunkSize, 4) | |
combined += format.bytes | |
combined += subchunk1ID.bytes | |
combined += toBytes(subchunk1Size, 4) | |
combined += toBytes(audioFormat, 2) | |
combined += toBytes(numChannels, 2) | |
combined += toBytes(sampleRate, 4) | |
combined += toBytes(byteRate, 4) | |
combined += toBytes(blockAlign, 2) | |
combined += toBytes(bitsPerSample, 2) | |
combined += subchunk2ID.bytes | |
combined += toBytes(subchunk2Size, 4) | |
combined += data | |
content = Slice.new(combined.to_unsafe, combined.size) | |
File.write("#{filename}.wav", content, mode: "w") | |
def toBytes(num, numBytes) | |
bytes = num.to_s(16) | |
bytes = bytes.size % 2 == 0 ? bytes : "0#{bytes}" | |
bytes = bytes.split(/(.{2})/) | |
bytes.delete("") | |
bytes.map!{|c| c.size != 2 ? "0#{c}" : c} | |
bytes.reverse! | |
while bytes.size < numBytes | |
bytes.push("00") | |
end | |
bytes.map{|c| c.hexbytes[0] } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment