Audio.tsx 10.1 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9
import {BlobResponse, blobFetcher} from '~/utils/fetch';
import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import {
    WithStyled,
    primaryActiveColor,
    primaryBackgroundColor,
    primaryColor,
    primaryFocusedColor,
    rem,
P
Peter Pan 已提交
10
    size,
P
Peter Pan 已提交
11 12 13 14 15 16 17 18
    textLightColor,
    textLighterColor
} from '~/utils/style';

import {AudioPlayer} from '~/utils/audio';
import Icon from '~/components/Icon';
import PuffLoader from 'react-spinners/PuffLoader';
import RangeSlider from '~/components/RangeSlider';
P
Peter Pan 已提交
19
import Slider from 'react-rangeslider';
P
Peter Pan 已提交
20 21 22 23 24 25 26
import SyncLoader from 'react-spinners/SyncLoader';
import Tippy from '@tippyjs/react';
import mime from 'mime-types';
import moment from 'moment';
import {saveAs} from 'file-saver';
import styled from 'styled-components';
import useRequest from '~/hooks/useRequest';
27
import {useTranslation} from 'react-i18next';
P
Peter Pan 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

const Container = styled.div`
    background-color: ${primaryBackgroundColor};
    border-radius: ${rem(8)};
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 ${rem(20)};

    > .control {
        font-size: ${rem(16)};
        line-height: 1;
        margin: 0 ${rem(10)};
        color: ${primaryColor};
        cursor: pointer;

        &.volumn {
            font-size: ${rem(20)};
        }

        &.disabled {
            color: ${textLightColor};
            cursor: not-allowed;
        }

        &:hover {
            color: ${primaryFocusedColor};
        }

        &:active {
            color: ${primaryActiveColor};
        }
    }

    > .slider {
        flex-grow: 1;
        padding: 0 ${rem(10)};
    }

    > .time {
        color: ${textLighterColor};
        font-size: ${rem(12)};
        margin: 0 ${rem(5)};
    }
`;

P
Peter Pan 已提交
74
const VolumnSlider = styled(Slider)`
P
Peter Pan 已提交
75 76 77 78
    margin: ${rem(15)} ${rem(18)};
    width: ${rem(4)};
    height: ${rem(100)};
    cursor: pointer;
P
Peter Pan 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    position: relative;
    background-color: #dbdeeb;
    outline: none;
    border-radius: ${rem(2)};
    user-select: none;

    --color: ${primaryColor};

    &:hover {
        --color: ${primaryFocusedColor};
    }

    &:active {
        --color: ${primaryActiveColor};
    }

    .rangeslider__fill {
        background-color: var(--color);
        position: absolute;
        bottom: 0;
        width: 100%;
        border-bottom-left-radius: ${rem(2)};
        border-bottom-right-radius: ${rem(2)};
        border-top: ${rem(4)} solid var(--color);
        box-sizing: content-box;
    }

    .rangeslider__handle {
        background-color: var(--color);
        ${size(rem(8), rem(8))}
        position: absolute;
        left: -${rem(2)};
        border-radius: 50%;
        outline: none;

        .rangeslider__handle-tooltip,
        .rangeslider__handle-label {
            display: none;
        }
    }

    .rangeslider__labels {
        display: none;
    }
P
Peter Pan 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
`;

const SLIDER_MAX = 100;

function formatDuration(seconds: number) {
    const duration = moment.duration(seconds, 'seconds');
    return (
        String(Math.floor(duration.asMinutes())).padStart(2, '0') + ':' + String(duration.seconds()).padStart(2, '0')
    );
}

export type AudioRef = {
    save(filename: string): void;
};

export type AudioProps = {
P
Peter Pan 已提交
139
    audioContext?: AudioContext;
P
Peter Pan 已提交
140 141 142 143 144 145
    src?: string;
    cache?: number;
    onLoading?: () => unknown;
    onLoad?: (audio: {sampleRate: number; duration: number}) => unknown;
};

P
Peter Pan 已提交
146 147 148
const Audio = React.forwardRef<AudioRef, AudioProps & WithStyled>(
    ({audioContext, src, cache, onLoading, onLoad, className}, ref) => {
        const {t} = useTranslation('common');
P
Peter Pan 已提交
149

P
Peter Pan 已提交
150 151 152
        const {data, error, loading} = useRequest<BlobResponse>(src ?? null, blobFetcher, {
            dedupingInterval: cache ?? 2000
        });
P
Peter Pan 已提交
153

P
Peter Pan 已提交
154 155 156 157 158 159
        useImperativeHandle(ref, () => ({
            save: (filename: string) => {
                if (data) {
                    const ext = data.type ? mime.extension(data.type) : null;
                    saveAs(data.data, filename.replace(/[/\\?%*:|"<>]/g, '_') + (ext ? `.${ext}` : ''));
                }
P
Peter Pan 已提交
160
            }
P
Peter Pan 已提交
161
        }));
P
Peter Pan 已提交
162

P
Peter Pan 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        const timer = useRef<number | null>(null);
        const player = useRef<AudioPlayer | null>(null);
        const [sliderValue, setSliderValue] = useState(0);
        const [offset, setOffset] = useState(0);
        const [duration, setDuration] = useState('00:00');
        const [decoding, setDecoding] = useState(false);
        const [playing, setPlaying] = useState(false);
        const [volumn, setVolumn] = useState(100);
        const [playAfterSeek, setPlayAfterSeek] = useState(false);

        const play = useCallback(() => player.current?.play(), []);
        const pause = useCallback(() => player.current?.pause(), []);
        const toggle = useCallback(() => player.current?.toggle(), []);
        const change = useCallback((value: number) => {
            if (!player.current) {
                return;
P
Peter Pan 已提交
179
            }
P
Peter Pan 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
            setOffset((value / SLIDER_MAX) * player.current.duration);
            setSliderValue(value);
        }, []);
        const startSeek = useCallback(() => {
            setPlayAfterSeek(playing);
            pause();
        }, [playing, pause]);
        const stopSeek = useCallback(() => {
            if (!player.current) {
                return;
            }
            player.current.seek(offset);
            if (playAfterSeek && offset < player.current.duration) {
                play();
            }
        }, [play, offset, playAfterSeek]);
        const toggleMute = useCallback(() => {
            if (player.current) {
                player.current.toggleMute();
                setVolumn(player.current.volumn);
            }
        }, []);
P
Peter Pan 已提交
202

P
Peter Pan 已提交
203 204 205 206 207
        const tick = useCallback(() => {
            if (player.current) {
                const current = player.current.current;
                setOffset(current);
                setSliderValue(Math.floor((current / player.current.duration) * SLIDER_MAX));
P
Peter Pan 已提交
208
            }
P
Peter Pan 已提交
209 210 211 212 213 214 215 216 217
        }, []);
        const startTimer = useCallback(() => {
            tick();
            timer.current = (globalThis.setInterval(tick, 250) as unknown) as number;
        }, [tick]);
        const stopTimer = useCallback(() => {
            if (player.current) {
                if (player.current.current >= player.current.duration) {
                    tick();
P
Peter Pan 已提交
218
                }
P
Peter Pan 已提交
219 220 221 222 223 224
            }
            if (timer.current) {
                globalThis.clearInterval(timer.current);
                timer.current = null;
            }
        }, [tick]);
P
Peter Pan 已提交
225

P
Peter Pan 已提交
226 227 228 229 230
        useEffect(() => {
            if (player.current) {
                player.current.volumn = volumn;
            }
        }, [volumn]);
P
Peter Pan 已提交
231

P
Peter Pan 已提交
232
        useEffect(() => {
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
            let p: AudioPlayer | null = null;
            if (data) {
                (async () => {
                    setDecoding(true);
                    onLoading?.();
                    setOffset(0);
                    setSliderValue(0);
                    setDuration('00:00');
                    p = new AudioPlayer({
                        context: audioContext,
                        onplay: () => {
                            setPlaying(true);
                            startTimer();
                        },
                        onstop: () => {
                            setPlaying(false);
                            stopTimer();
                        }
                    });
                    const buffer = await data.data.arrayBuffer();
                    await p.load(buffer, data.type != null ? mime.extension(data.type) || undefined : undefined);
                    setDecoding(false);
                    setDuration(formatDuration(p.duration));
                    onLoad?.({sampleRate: p.sampleRate, duration: p.duration});
                    player.current = p;
                })();
P
Peter Pan 已提交
259
            }
260 261 262 263 264 265 266
            return () => {
                if (p) {
                    setPlaying(false);
                    p.dispose();
                    player.current = null;
                }
            };
P
Peter Pan 已提交
267
        }, [data, startTimer, stopTimer, onLoading, onLoad, audioContext]);
P
Peter Pan 已提交
268

P
Peter Pan 已提交
269 270 271 272 273 274 275 276 277
        const volumnIcon = useMemo(() => {
            if (volumn === 0) {
                return 'mute';
            }
            if (volumn <= 50) {
                return 'volumn-low';
            }
            return 'volumn';
        }, [volumn]);
P
Peter Pan 已提交
278

P
Peter Pan 已提交
279 280 281 282 283 284 285 286 287 288 289 290
        if (loading) {
            return <SyncLoader color={primaryColor} size="15px" />;
        }

        if (error) {
            return <div>{t('common:error')}</div>;
        }

        return (
            <Container className={className}>
                <a className={`control ${decoding ? 'disabled' : ''}`} onClick={toggle}>
                    {decoding ? <PuffLoader size="16px" /> : <Icon type={playing ? 'pause' : 'play'} />}
P
Peter Pan 已提交
291
                </a>
P
Peter Pan 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
                <div className="slider">
                    <RangeSlider
                        min={0}
                        max={SLIDER_MAX}
                        step={1}
                        value={sliderValue}
                        disabled={decoding}
                        onChange={change}
                        onChangeStart={startSeek}
                        onChangeComplete={stopSeek}
                    />
                </div>
                <span className="time">
                    {formatDuration(offset)}/{duration}
                </span>
                <Tippy
                    placement="top"
                    animation="shift-away-subtle"
                    interactive
                    hideOnClick={false}
                    content={
                        <VolumnSlider
                            value={volumn}
                            min={0}
                            max={100}
                            step={1}
                            onChange={setVolumn}
                            orientation="vertical"
                        />
                    }
                >
                    <a className="control volumn" onClick={toggleMute}>
                        <Icon type={volumnIcon} />
                    </a>
                </Tippy>
            </Container>
        );
    }
);
P
Peter Pan 已提交
331 332

export default Audio;