113 lines
3.1 KiB
TypeScript
113 lines
3.1 KiB
TypeScript
import useMitt from "@/modules/mitt";
|
|
import { useIpc } from '@/modules/ipc';
|
|
import { showRecIcon, hideRecIcon } from "./animations";
|
|
// import useMediaRecorder from "./mediarecorder";
|
|
import { onMounted, onUnmounted, ref, Ref } from "vue";
|
|
import keyboardNameMap from "../keyBoardMaps/keyboardNameMap";
|
|
import { renderMessage, clientMessage } from '@/modules/message';
|
|
import { AudioData } from "@/types";
|
|
|
|
|
|
|
|
export default function useAudioInputController (typing: Ref) {
|
|
|
|
let mediaRecorder: any;
|
|
let buffer = '';
|
|
|
|
// For sending messages.
|
|
const { post, invoke } = useIpc();
|
|
const { emitter } = useMitt();
|
|
|
|
const recording = ref(false);
|
|
|
|
// initiate media recorder
|
|
if (navigator.mediaDevices) {
|
|
console.log("Initializing media recorder.");
|
|
|
|
const usrOptions: any = {
|
|
audio: true,
|
|
video: false
|
|
}
|
|
|
|
navigator.mediaDevices.getUserMedia(usrOptions).then((stream: any) => {
|
|
|
|
const context = new AudioContext();
|
|
const source = context.createMediaStreamSource(stream);
|
|
const processor = context.createScriptProcessor(1024, 1, 1);
|
|
|
|
source.connect(processor);
|
|
processor.connect(context.destination);
|
|
|
|
processor.onaudioprocess = (e: AudioProcessingEvent) => {
|
|
if (recording.value) {
|
|
const arr = new Uint16Array(e.inputBuffer);
|
|
buffer += String.fromCharCode.apply(null, new Float32Array(e.inputBuffer));
|
|
} else buffer = '';
|
|
};
|
|
|
|
});
|
|
|
|
}
|
|
|
|
//---Callbacks-----------------------------------------------
|
|
|
|
const onKeyDown = (e: KeyboardEvent) => {
|
|
const cmd = keyboardNameMap[e.keyCode];
|
|
|
|
// Start recording on space bar.
|
|
if (cmd == "SPACE" && !typing.value && !recording.value) {
|
|
|
|
console.log("INPT:Starting record, filling buffer.")
|
|
recording.value = true;
|
|
showRecIcon();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const onKeyUp = async (e: KeyboardEvent) => {
|
|
const cmd = keyboardNameMap[e.keyCode];
|
|
|
|
// Stop recording on space up.
|
|
if (cmd == "SPACE" && recording.value) {
|
|
|
|
// get audio from buffer then stop recording
|
|
console.log("INPT:Stopping record.")
|
|
const audio = buffer;
|
|
recording.value = false;
|
|
hideRecIcon()
|
|
|
|
// render a place holder message
|
|
const message = renderMessage(
|
|
"",
|
|
"",
|
|
"",
|
|
"sf"
|
|
);
|
|
|
|
emitter.emit("self-message", message);
|
|
|
|
console.log(`Posting audio: ${audio}`);
|
|
console.log(typeof audio);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
//-----------------------------------------------------------
|
|
|
|
onMounted(() => {
|
|
window.addEventListener("keydown", onKeyDown);
|
|
window.addEventListener("keyup", onKeyUp);
|
|
})
|
|
|
|
onUnmounted(() => {
|
|
window.removeEventListener("keydown", onKeyDown);
|
|
window.removeEventListener("keyup", onKeyUp);
|
|
});
|
|
|
|
return {
|
|
recording
|
|
}
|
|
|
|
}
|