Sha256: 7e653d1cc44fc55f654ec27de812b519612c664d0ac78848d33b296b1e59e620

Contents?: true

Size: 1.17 KB

Versions: 2

Compression:

Stored size: 1.17 KB

Contents

require 'mp3info'
require 'pathname'
require 'riff/reader'

module Scissor
  class SoundFile
    class Mp3 < SoundFile
      def length
        info.length
      end

      def mono?
        info.channel_mode == 'Single Channel'
      end

      private

      def info
        @info ||= Mp3Info.new(@filename.to_s)
      end
    end

    class Wav < SoundFile
      def length
        data.length / fmt.body.unpack('s2i2')[3].to_f
      end

      def mono?
        fmt.body.unpack('s2')[1] == 1
      end

      private

      def riff
        @riff ||= Riff::Reader.open(@filename ,"r")
      end

      def data
        @data ||= riff.root_chunk['data']
      end

      def fmt
        @fmt ||= riff.root_chunk['fmt ']
      end
    end

    SUPPORTED_FORMATS = {
      :mp3 => Mp3,
      :wav => Wav
    }

    class Error < StandardError; end
    class UnknownFormat < Error; end

    def self.new_from_filename(filename)
      ext = filename.extname.sub(/^\./, '').downcase

      unless klass = SUPPORTED_FORMATS[ext.to_sym]
        raise UnknownFormat
      end

      klass.new(filename)
    end

    def initialize(filename)
      @filename = Pathname.new(filename)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
scissor-0.4.0 lib/scissor/sound_file.rb
scissor-0.3.0 lib/scissor/sound_file.rb