Module: Muze::IO::AudioWriter

Defined in:
lib/muze/io/audio_writer.rb

Overview

WAV writer for lightweight effects/analysis result inspection.

Class Method Summary collapse

Class Method Details

.write(path, y, sr:, normalize: false, format: :wav) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/muze/io/audio_writer.rb', line 14

def write(path, y, sr:, normalize: false, format: :wav)
  raise Muze::ParameterError, "sr must be positive" unless sr.is_a?(Integer) && sr.positive?
  raise Muze::ParameterError, "normalize must be true or false" unless [true, false].include?(normalize)

  format_label = format.to_s.downcase.to_sym
  raise Muze::UnsupportedFormatError, "only WAV output is supported" unless %i[wav wave].include?(format_label)

  signal = Muze::Core::Audio.validate_audio!(y, allow_empty: true)
  signal = Muze::Core::Audio.normalize(signal) if normalize
  channels = signal.ndim == 2 ? signal.shape[1] : 1
  samples = flatten_samples(signal)
  sample_format = Wavify::Core::Format.new(channels:, sample_rate: sr, bit_depth: 32, sample_format: :float)
  buffer = Wavify::Core::SampleBuffer.new(samples, sample_format)
  Wavify::Codecs::Wav.write(output_target(path), buffer)
  path
rescue Muze::Error
  raise
rescue SystemCallError, Wavify::Error => e
  raise Muze::AudioLoadError, "Failed to write WAV output #{path}: #{e.message}"
end