Skip to content
Snippets Groups Projects
Commit b15796cf authored by MonaS8's avatar MonaS8
Browse files

Frontend: added measureVolume

parent 73c8721a
No related branches found
No related tags found
No related merge requests found
import Peer from 'peerjs';
import { reactive } from 'vue';
import { reactive, ref } from 'vue';
import { Socket } from 'socket.io-client';
import { ChannelUser, Student } from '@/composables/channel/channel';
export const useWebcam = () => {
let webcamsLoaded = false;
const streams: Record<string, MediaStream> = reactive({});
const volume = ref(0);
let user: ChannelUser | null = null;
let socket: Socket | null = null;
......@@ -34,6 +35,7 @@ export const useWebcam = () => {
video: true,
audio: true,
});
measureVolume(stream);
if (!user?.video) {
stream.getVideoTracks().forEach((track) => (track.enabled = false));
......@@ -151,6 +153,37 @@ export const useWebcam = () => {
webcamsLoaded = false;
}
function measureVolume(stream: MediaStream) {
const audioCtx = new AudioContext();
const source = audioCtx.createMediaStreamSource(stream);
const analyser = audioCtx.createAnalyser();
source.connect(analyser);
const dataArray = new Uint8Array(analyser.fftSize);
let isTalking = false;
function updateVolume() {
analyser.getByteTimeDomainData(dataArray);
let sum = 0;
for (let i = 0; i < dataArray.length; i++) {
sum += (dataArray[i] - 128) ** 2;
}
volume.value = Math.sqrt(sum / dataArray.length);
if (volume.value > 10 && !isTalking) {
isTalking = true;
socket?.emit('start-talking',{volume: volume.value});
} else if (volume.value <= 10 && isTalking) {
isTalking = false;
socket?.emit('stop-talking',{volume: volume.value});
}
}
updateVolume();
setInterval(updateVolume, 100);
}
function getVolume(): number {
return volume.value;
}
return {
streams,
init,
......@@ -160,5 +193,6 @@ export const useWebcam = () => {
toggleAudio,
disableAudioFor,
stop,
getVolume,
};
};
......@@ -232,6 +232,7 @@
</div>
</div>
</template>
<p class="text-white">(volume: {{ channel.webcam.getVolume().toFixed(2) }})</p>
</div>
<span class="flex-grow-1"></span>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment