         @state = 'inactive'
         @encoderWorker.postMessage(['dump', @audioCtx.sampleRate])
         clearInterval(@slicing)
-
-        # TODO: There should be a more robust way to handle this
-        # Without something like this, I think  the last recorded sample could be lost due to timing
-        # setTimeout(() -> {
-        #   state = 'inactive'
-        #   mediaRecorder.encoderWorker.postMessage(['dump', audioCtx.sampleRate])
-        # }, 100)
-      return
-
+      return
+
+    # Called each time a chunk of recording becomes available
     _onDataAvailable: (evt) ->
-      # console.log('state', mediaRecorder.state)
-      # console.log('evt.data', evt.data)
       @chunks.push(evt.data)
       @chunkType = evt.data.type
 
       if (@state != 'inactive')
         return
 
-      blob = new Blob(@chunks, {'type': @chunkType})
+      blob = new Blob(@chunks, { 'type': @chunkType })
       blobUrl = URL.createObjectURL(blob)
       recording = {
         ts: new Date().getTime(),

        micGain: 1.0,
        processorBufferSize: 2048,
        stopTracksAndCloseCtxWhenFinished: true,
        userMediaConstraints:
          audio: true
      return

    createWorker: (fn) ->
      js = fn
        .toString()
        .replace(/^function\s*\(\)\s*{/, '')
        .replace(/}$/, '')
      blob = new Blob([js])
      return new Worker(URL.createObjectURL(blob))

    startRecording: (timeslice) ->
      if (@state != 'inactive')
        return


# Parts adapted from https://github.com/kaliatech/web-audio-recording-tests

angular.module("doubtfire.common.services.recorder-service", [])
#
# Services for working with cross-platform, media Recording APIs
#
.factory("recorderService", ($rootScope, $timeout, $sce) ->
  return class RecorderService
    constructor: () ->
      window.AudioContext = window.AudioContext || window.webkitAudioContext

      @em = document.createDocumentFragment()
      @state = 'inactive'
      @audioCtx = {}
      @chunks = []
      @chunkType = ''

