|
'use strict'; |
|
|
|
/* Directives */ |
|
|
|
|
|
angular.module('myApp.directives', []). |
|
directive('recorder', ['$interval', '$window', function($interval, $window) { |
|
return { |
|
restrict: "E", |
|
|
|
link: function($scope, element, attributes) { |
|
$scope.recorder = null; |
|
$scope.audioContext = null; |
|
$scope.isPlaying = false; |
|
$scope.isRecording = false; |
|
$scope.hasRecorded = false; |
|
$scope.currentRecordingLength = 0; |
|
$scope.currentRecordingIntervalId = null; |
|
|
|
function setupRecorder (stream) { |
|
var audioInput, audioGain; |
|
|
|
audioInput = $scope.audioContext.createMediaStreamSource(stream); |
|
audioGain = $scope.audioContext.createGain(); |
|
|
|
audioGain.gain.value = 0; |
|
audioInput.connect(audioGain); |
|
audioGain.connect($scope.audioContext.destination); |
|
|
|
$scope.recorder = new Recorder(audioInput); |
|
} |
|
|
|
try { |
|
$window.AudioContext = $window.AudioContext || $window.webkitAudioContext; |
|
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia |
|
|
|
$scope.audioContext = new AudioContext(); |
|
|
|
navigator.getUserMedia({ audio: true }, setupRecorder, function(err) {}); |
|
} |
|
catch (error) { |
|
return false; |
|
} |
|
|
|
$scope.formatSeconds = function (seconds) { |
|
var minutes = parseInt( seconds / 60 ) % 60; |
|
var seconds = seconds % 60; |
|
|
|
var result = (minutes < 10 ? "0" + minutes : minutes) + ":" |
|
+ (seconds < 10 ? "0" + seconds : seconds); |
|
|
|
return result; |
|
} |
|
|
|
$scope.toggleRecording = function() { |
|
if (!this.recorder) { return false; } |
|
|
|
if (this.isRecording === false) { |
|
this.hasRecorded = true; |
|
|
|
this.recorder.record(); |
|
|
|
this.currentRecordingIntervalId = $interval(function() { |
|
$scope.currentRecordingLength++; |
|
}, 1000); |
|
} |
|
else { |
|
this.recorder.stop(); |
|
$interval.cancel(this.currentRecordingIntervalId); |
|
} |
|
|
|
this.isRecording = !this.isRecording; |
|
} |
|
|
|
$scope.playbackRecording = function() { |
|
if (this.hasRecorded) { |
|
this.recorder.getBuffer(function(buffers) { |
|
var newSource, newBuffer; |
|
|
|
newSource = $scope.audioContext.createBufferSource(); |
|
newBuffer = $scope.audioContext.createBuffer(2, buffers[0].length, $scope.audioContext.sampleRate); |
|
|
|
newBuffer.getChannelData(0).set(buffers[0]); |
|
newBuffer.getChannelData(1).set(buffers[1]); |
|
newSource.buffer = newBuffer; |
|
|
|
newSource.connect($scope.audioContext.destination); |
|
newSource.start(0); |
|
}); |
|
} |
|
} |
|
|
|
$scope.submitRecording = function() { |
|
this.recorder.exportWAV(function(wav) { |
|
var url = URL.createObjectURL(wav); |
|
var win = $window.open(url, '_blank'); |
|
win.focus(); |
|
}); |
|
} |
|
|
|
$scope.clearRecording = function() { |
|
$scope.hasRecorded = false; |
|
$scope.currentRecordingLength = 0; |
|
$scope.recorder.clear(); |
|
} |
|
}, |
|
|
|
templateUrl: "partials/recorder.html", |
|
replace: true, |
|
} |
|
}]); |