Skip to content

Instantly share code, notes, and snippets.

@hitode909
Created June 9, 2012 01:50
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 hitode909/2899056 to your computer and use it in GitHub Desktop.
Save hitode909/2899056 to your computer and use it in GitHub Desktop.
require 'wav-file'
def cut
f = open("input.wav")
format = WavFile::readFormat(f)
dataChunk = WavFile::readDataChunk(f)
f.close
bit = 's*' if format.bitPerSample == 16 # int16_t
bit = 'c*' if format.bitPerSample == 8 # signed char
wavs = dataChunk.data.unpack(bit) # read binary
step = format.hz * format.channel / 20
loop_total_count = wavs.length / step
length = wavs.length
max = 2**(format.bitPerSample-1) * step
parts = []
dest = []
last_is_on = false
ontime = 0
while wavs.length > 0 do
chunk = wavs.slice!(0, step)
volume = chunk.inject(0){ |a, b| a + b.abs } / max.to_f
is_on = volume > 0.02
ontime += step if is_on
if not last_is_on and is_on
if ontime < format.hz * format.channel * 0.5
puts "write volume: #{volume} samples: #{ontime}"
parts << dest
end
dest = []
ontime = 0
end
dest.concat(chunk)
last_is_on = is_on
end
dest.concat chunk
parts
end
unless File.exists?('dump.txt')
open('dump.txt', 'w'){ |f|
f.write Marshal.dump(cut)
}
end
f = open("input.wav")
format = WavFile::readFormat(f)
dataChunk = WavFile::readDataChunk(f)
f.close
bit = 's*' if format.bitPerSample == 16 # int16_t
bit = 'c*' if format.bitPerSample == 8 # signed char
parts = Marshal.load(open('dump.txt').read)
secs = 60
total_dest = []
index = (parts.length * 0.7).to_i
while total_dest.length < format.hz * format.channel * secs
total_dest.concat(parts[index])
index += [1, -1].sample
index = 0 if index < 0
index = parts.length-1 if index > parts.length
p [index, parts[index].length ]
end
dataChunk.data = total_dest.pack(bit)
open("output.wav", "w"){|out|
WavFile::write(out, format, [dataChunk])
}
dest = []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment