|
| 1 | +/* |
| 2 | +Copyright 2021 The Matrix.org Foundation C.I.C. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import React from "react"; |
| 18 | +import {IFrequencyPackage, VoiceRecorder} from "../../../voice/VoiceRecorder"; |
| 19 | +import {replaceableComponent} from "../../../utils/replaceableComponent"; |
| 20 | +import {arrayFastResample, arraySeed} from "../../../utils/arrays"; |
| 21 | +import {percentageOf} from "../../../utils/numbers"; |
| 22 | + |
| 23 | +interface IProps { |
| 24 | + recorder: VoiceRecorder |
| 25 | +} |
| 26 | + |
| 27 | +interface IState { |
| 28 | + heights: number[]; |
| 29 | +} |
| 30 | + |
| 31 | +const DOWNSAMPLE_TARGET = 35; // number of bars |
| 32 | + |
| 33 | +@replaceableComponent("views.voice_messages.FrequencyBars") |
| 34 | +export default class FrequencyBars extends React.PureComponent<IProps, IState> { |
| 35 | + public constructor(props) { |
| 36 | + super(props); |
| 37 | + |
| 38 | + this.state = {heights: arraySeed(0, DOWNSAMPLE_TARGET)}; |
| 39 | + this.props.recorder.frequencyData.onUpdate(this.onFrequencyData); |
| 40 | + } |
| 41 | + |
| 42 | + private onFrequencyData = (freq: IFrequencyPackage) => { |
| 43 | + // We're downsampling from about 1024 points to about 35, so this function is fine (see docs/impl) |
| 44 | + const bars = arrayFastResample(Array.from(freq.dbBars), DOWNSAMPLE_TARGET); |
| 45 | + this.setState({ |
| 46 | + // Values are somewhat arbitrary, but help decide what shape the graph should be |
| 47 | + heights: bars.map(b => percentageOf(b, -150, -70) * 100), |
| 48 | + }); |
| 49 | + }; |
| 50 | + |
| 51 | + public render() { |
| 52 | + return <div className='mx_FrequencyBars'> |
| 53 | + {this.state.heights.map((h, i) => { |
| 54 | + return <span key={i} style={{height: h + '%'}} className='mx_FrequencyBars_bar' />; |
| 55 | + })} |
| 56 | + </div>; |
| 57 | + } |
| 58 | +} |
0 commit comments