Class: DSP::Spectrum

Inherits:
Object
  • Object
show all
Defined in:
lib/dsprb/spectrum.rb,
sig/dsprb.rbs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size, transform: nil) ⇒ Spectrum

Returns a new instance of Spectrum.

Parameters:

  • (::Integer)
  • transform: (_Transform, nil) (defaults to: nil)


7
8
9
10
11
12
# File 'lib/dsprb/spectrum.rb', line 7

def initialize(size, transform: nil)
  @size = Integer(size)
  @transform = transform || Fourier::Radix2.new(@size)
  @bins = (@size / 2) + 1
  freeze
end

Instance Attribute Details

#bins::Integer (readonly)

Returns the value of attribute bins.

Returns:

  • (::Integer)


5
6
7
# File 'lib/dsprb/spectrum.rb', line 5

def bins
  @bins
end

#size::Integer (readonly)

Returns the value of attribute size.

Returns:

  • (::Integer)


5
6
7
# File 'lib/dsprb/spectrum.rb', line 5

def size
  @size
end

#transform_Transform (readonly)

Returns the value of attribute transform.

Returns:



5
6
7
# File 'lib/dsprb/spectrum.rb', line 5

def transform
  @transform
end

Instance Method Details

#bin_of(frequency, sample_rate) ⇒ ::Integer

Parameters:

  • (::Numeric)
  • (::Numeric)

Returns:

  • (::Integer)


33
# File 'lib/dsprb/spectrum.rb', line 33

def bin_of(frequency, sample_rate) = (frequency * @size / sample_rate.to_f).round

#frequencies(sample_rate) ⇒ ::Array[::Float]

Parameters:

  • (::Numeric)

Returns:

  • (::Array[::Float])


31
# File 'lib/dsprb/spectrum.rb', line 31

def frequencies(sample_rate) = Array.new(@bins) { |bin| bin * sample_rate / @size.to_f }

#magnitude(frame) ⇒ spectrum

Parameters:

  • (frame)

Returns:

  • (spectrum)


29
# File 'lib/dsprb/spectrum.rb', line 29

def magnitude(frame) = power(frame).map { |value| Math.sqrt(value) }

#power(frame) ⇒ spectrum

Parameters:

  • (frame)

Returns:

  • (spectrum)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/dsprb/spectrum.rb', line 14

def power(frame)
  real = Array.new(@size, 0.0)
  imaginary = Array.new(@size, 0.0)
  limit = [frame.length, @size].min
  index = 0
  while index < limit
    real[index] = frame[index].to_f
    index += 1
  end

  @transform.call(real, imaginary)

  Array.new(@bins) { |bin| (real[bin] * real[bin]) + (imaginary[bin] * imaginary[bin]) }
end