Class: Wavesync::Audio

Inherits:
Object
  • Object
show all
Defined in:
lib/wavesync/audio.rb

Constant Summary collapse

SUPPORTED_FORMATS =
%w[.m4a .mp3 .wav .aif .aiff].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Audio

Returns a new instance of Audio.



18
19
20
21
22
# File 'lib/wavesync/audio.rb', line 18

def initialize(file_path)
  @file_path = file_path
  @file_ext = File.extname(@file_path).downcase
  @audio = FFMPEG::Movie.new(file_path)
end

Class Method Details

.find_all(library_path) ⇒ Object



13
14
15
16
# File 'lib/wavesync/audio.rb', line 13

def self.find_all(library_path)
  Dir.glob(File.join(library_path, '**', '*'))
     .select { |f| SUPPORTED_FORMATS.include?(File.extname(f).downcase) }
end

Instance Method Details

#bit_depthObject



32
33
34
# File 'lib/wavesync/audio.rb', line 32

def bit_depth
  @bit_depth ||= calculate_bit_depth
end

#bpmObject



36
37
38
39
40
# File 'lib/wavesync/audio.rb', line 36

def bpm
  return @bpm if defined?(@bpm)

  @bpm = bpm_from_file
end

#durationObject



24
25
26
# File 'lib/wavesync/audio.rb', line 24

def duration
  @audio.duration
end

#formatObject



42
43
44
45
46
47
48
# File 'lib/wavesync/audio.rb', line 42

def format
  AudioFormat.new(
    file_type: @file_ext.delete_prefix('.'),
    sample_rate: sample_rate,
    bit_depth: bit_depth
  )
end

#sample_rateObject



28
29
30
# File 'lib/wavesync/audio.rb', line 28

def sample_rate
  @sample_rate ||= @audio.audio_sample_rate
end

#transcode(target_path, target_sample_rate: nil, target_file_type: nil, target_bit_depth: nil, padding_seconds: nil) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/wavesync/audio.rb', line 64

def transcode(target_path, target_sample_rate: nil, target_file_type: nil, target_bit_depth: nil, padding_seconds: nil)
  options = build_transcode_options(target_sample_rate, target_bit_depth, padding_seconds)
  ext = target_file_type || @file_ext.delete_prefix('.')
  temp_path = File.join(
    Dir.tmpdir,
    "wavesync_transcode_#{SecureRandom.hex}.#{ext}"
  )

  begin
    @audio.transcode(temp_path, options)
    FileUtils.install(temp_path, target_path)
    true
  rescue Errno::ENOENT
    puts 'Errno::ENOENT'
    false
  ensure
    FileUtils.rm_f(temp_path)
  end
end

#write_bpm(bpm) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/wavesync/audio.rb', line 50

def write_bpm(bpm)
  case @file_ext
  when '.m4a'
    write_bpm_to_m4a(bpm)
  when '.mp3'
    write_bpm_to_mp3(bpm)
  when '.wav'
    write_bpm_to_wav(bpm)
  when '.aif', '.aiff'
    write_bpm_to_aiff(bpm)
  end
  @bpm = bpm
end