Last active
July 11, 2022 13:47
-
-
Save raviteja83/09789f27be4d8f7a83465fbf0f8950d4 to your computer and use it in GitHub Desktop.
A plugin to analyse audio level for 100ms local peer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HMSAudioPluginType } from "@100mslive/react-sdk"; | |
export class AnalyserPlugin { | |
name = "analyser-plugin"; | |
onChange = () => {}; | |
analyserNode = undefined; | |
constructor(onChange) { | |
this.onChange = onChange; | |
} | |
checkSupport() { | |
return { isSupported: true }; | |
} | |
async processAudioTrack(ctx, source) { | |
if (!ctx) { | |
throw new Error("Audio context is not created"); | |
} | |
if (!source) { | |
throw new Error("source is not defined"); | |
} | |
this.analyserNode = ctx.createAnalyser(); | |
source.connect(this.analyserNode); | |
this.calculateAudioLevel(); | |
return source; | |
} | |
calculateAudioLevel = () => { | |
if (!this.analyserNode) { | |
return; | |
} | |
const data = new Uint8Array(this.analyserNode.fftSize); | |
this.analyserNode.getByteTimeDomainData(data); | |
const lowest = 0.009; | |
let max = lowest; | |
for (const frequency of data) { | |
max = Math.max(max, (frequency - 128) / 128); | |
} | |
const normalized = (Math.log(lowest) - Math.log(max)) / Math.log(lowest); | |
const percent = Math.ceil(Math.min(Math.max(normalized * 100, 0), 100)); | |
this.onChange(percent); | |
requestAnimationFrame(this.calculateAudioLevel); | |
}; | |
init() {} | |
getName() { | |
return this.name; | |
} | |
getPluginType() { | |
return HMSAudioPluginType.ANALYZE; | |
} | |
stop() { | |
this.analyserNode?.disconnect(); | |
this.analyserNode = undefined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment