Class: Noyes::SpeechTrimmer

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_impl/speech_trimmer.rb

Overview

SpeechTrimmer trims non-speech from both ends of an audio stream. Each time you enqueue audio into it you should dequeue audio out of it until dequeue returns nil. Then check for eos. If eos is true you are done. SpeechTrimmer is designed to work efficiently with live audio.

Instance Method Summary collapse

Constructor Details

#initialize(frequency = 16000) ⇒ SpeechTrimmer

Returns a new instance of SpeechTrimmer.


7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/ruby_impl/speech_trimmer.rb', line 7

def initialize frequency=16000
  @leader = 5  # Cents of leading silence to retain.
  @trailer = 5  # Cents of trailing silence to retain.
  @speech_started = false
  @cent_marker = BentCentMarker.new
  @false_count=0
  @true_count=0
  @queue = []
  @eos_reached = false
  @scs = 20 # Centiseconds of speech before detection of utterance.
  @ecs = 50 # Centiseconds of silence before end detection.
  @segmenter = Segmenter.new(frequency/100, frequency/100)
end

Instance Method Details

#<<(pcm) ⇒ Object


21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ruby_impl/speech_trimmer.rb', line 21

def << pcm
  return if eos?
  segments = @segmenter << pcm
  return unless segments
  segments.inject [] do |memo, centisec|
    enqueue centisec unless eos?
    while x = dequeue
      memo << x
    end
    break memo if eos?
    memo
  end
end

#dequeueObject


60
61
62
63
64
# File 'lib/ruby_impl/speech_trimmer.rb', line 60

def dequeue
  if @eos_reached || (@speech_started && @queue.size > @ecs)
    @queue.shift
  end
end

#enqueue(pcm) ⇒ Object


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ruby_impl/speech_trimmer.rb', line 35

def enqueue pcm
  return if @eos_reached
  @queue << pcm
  if @cent_marker << pcm
    @false_count = 0
    @true_count += 1
  else
    @false_count += 1
    @true_count = 0
  end
  if @speech_started
    if @false_count == @ecs
      @eos_reached = true      # only keep trailer number of cents once eos is detected.

      @queue = @queue[0, @queue.size - @ecs + @trailer]
    end
  elsif @true_count > @scs    # Discard most begining silence, keeping just a tad.

    if @leader + @scs < @queue.size
      start = @queue.size - @leader - 1 - @scs
      @queue = @queue[start,@queue.size - start]
    end
    @speech_started = true
  end
end

#eos?Boolean

Returns:

  • (Boolean)

65
66
67
# File 'lib/ruby_impl/speech_trimmer.rb', line 65

def eos?
  @eos_reached
end