audio.ts 6.9 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * Copyright 2020 Baidu Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

P
Peter Pan 已提交
17 18
// cSpell:words mpga

P
Peter Pan 已提交
19
interface AudioPlayerOptions {
P
Peter Pan 已提交
20
    context?: AudioContext;
P
Peter Pan 已提交
21
    volume?: number;
P
Peter Pan 已提交
22 23 24 25 26 27 28 29 30
    onplay?: () => void;
    onstop?: () => void;
}

export class AudioPlayer {
    protected context: AudioContext;
    private gain: GainNode;
    private source: AudioBufferSourceNode | null = null;
    private buffer: AudioBuffer | null = null;
P
Peter Pan 已提交
31
    private decodedSampleRate: number = Number.NaN;
P
Peter Pan 已提交
32
    private contextFromOptions: boolean;
P
Peter Pan 已提交
33 34 35 36 37

    private startAt = 0;
    private stopAt = 0;
    private offset = 0;

P
Peter Pan 已提交
38
    private toggleVolume = 100;
P
Peter Pan 已提交
39 40 41

    public playing = false;

P
Peter Pan 已提交
42
    public readonly options: Required<AudioPlayerOptions>;
P
Peter Pan 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

    get current() {
        if (this.playing) {
            return this.context.currentTime - this.startAt + this.offset;
        }
        return this.offset;
    }

    get duration() {
        if (!this.buffer) {
            return Number.NaN;
        }
        return this.buffer.duration;
    }

    get sampleRate() {
        if (!this.buffer) {
            return Number.NaN;
        }
P
Peter Pan 已提交
62
        return this.decodedSampleRate;
P
Peter Pan 已提交
63 64
    }

P
Peter Pan 已提交
65
    get volume() {
P
Peter Pan 已提交
66 67
        return this.gain.gain.value * 100;
    }
P
Peter Pan 已提交
68
    set volume(value: number) {
P
Peter Pan 已提交
69 70 71 72 73 74 75 76
        if (value > 100) {
            value = 100;
        } else if (value < 0) {
            value = 0;
        }
        this.gain.gain.value = value / 100;
    }

P
Peter Pan 已提交
77
    constructor(options?: AudioPlayerOptions) {
P
Peter Pan 已提交
78
        this.options = {
P
Peter Pan 已提交
79
            context: options?.context ?? new AudioContext(),
P
Peter Pan 已提交
80
            volume: 100,
P
Peter Pan 已提交
81 82
            onplay: () => void 0,
            onstop: () => void 0,
P
Peter Pan 已提交
83 84
            ...options
        };
P
Peter Pan 已提交
85 86
        this.contextFromOptions = !!options?.context;
        this.context = this.options.context;
P
Peter Pan 已提交
87
        this.gain = this.context.createGain();
P
Peter Pan 已提交
88
        this.volume = this.options.volume;
P
Peter Pan 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102
    }

    private reset() {
        if (this.buffer) {
            if (this.playing) {
                this.source?.stop(0);
            }
            this.startAt = 0;
            this.stopAt = 0;
            this.offset = 0;
            this.buffer = null;
        }
    }

P
Peter Pan 已提交
103 104 105 106 107 108 109 110 111 112 113
    static getWavSampleRate(buffer: ArrayBuffer) {
        const intArr = new Int8Array(buffer);
        const sampleRateArr = intArr.slice(24, 28);
        return (
            (sampleRateArr[0] & 0xff) |
            ((sampleRateArr[1] & 0xff) << 8) |
            ((sampleRateArr[2] & 0xff) << 16) |
            ((sampleRateArr[3] & 0xff) << 24)
        );
    }

P
Peter Pan 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    static getMp3SampleRate(buffer: ArrayBuffer) {
        let arr = new Uint8Array(buffer);
        if (String.fromCharCode.apply(null, Array.from(arr.slice(0, 3))) === 'ID3') {
            arr = arr.slice(10);
            let i = 0;
            while (arr[i] !== 0x00) {
                const size = arr[i + 4] * 0x100000000 + arr[i + 5] * 0x10000 + arr[i + 6] * 0x100 + arr[i + 7];
                i += 10 + size;
            }
        }
        let j = 0;
        while (arr[j++] !== 0xff) {}
        j--;
        const header = arr.slice(j, j + 4);
        const version = (header[1] & 0b00011000) >> 3;
        const sampleRate = (header[2] & 0b00001100) >> 2;
        if (version === 0b11) {
            if (sampleRate === 0b00) {
                return 44100;
            } else if (sampleRate === 0b01) {
                return 48000;
            } else if (sampleRate === 0b10) {
                return 32000;
            }
        } else if (version === 0b10) {
            if (sampleRate === 0b00) {
                return 22050;
            } else if (sampleRate === 0b01) {
                return 24000;
            } else if (sampleRate === 0b10) {
                return 16000;
            }
        } else if (version === 0b00) {
            if (sampleRate === 0b00) {
                return 11025;
            } else if (sampleRate === 0b01) {
                return 12000;
            } else if (sampleRate === 0b10) {
                return 8000;
            }
        }
        return Number.NaN;
    }

P
Peter Pan 已提交
158
    load(buffer: ArrayBuffer, type?: string) {
P
Peter Pan 已提交
159
        this.reset();
P
Peter Pan 已提交
160
        if (type === 'wav') {
P
Peter Pan 已提交
161
            this.decodedSampleRate = AudioPlayer.getWavSampleRate(buffer);
P
Peter Pan 已提交
162 163
        } else if (type === 'mpga' || type === 'mp3') {
            this.decodedSampleRate = AudioPlayer.getMp3SampleRate(buffer);
P
Peter Pan 已提交
164 165 166
        } else {
            this.decodedSampleRate = Number.NaN;
        }
P
Peter Pan 已提交
167 168 169 170 171 172 173 174 175 176
        // safari doesn't return promise here
        return new Promise<void>((resolve, reject) => {
            this.context.decodeAudioData(
                buffer,
                audioBuffer => {
                    this.buffer = audioBuffer;
                    resolve();
                },
                reject
            );
P
Peter Pan 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190
        });
    }

    play() {
        if (!this.buffer) {
            throw new Error('No audio loaded');
        }
        this.source = this.context.createBufferSource();
        this.source.buffer = this.buffer;
        this.source.connect(this.gain).connect(this.context.destination);
        this.source.addEventListener('ended', () => {
            this.stopAt = this.context.currentTime;
            this.offset += this.stopAt - this.startAt;
            this.playing = false;
P
Peter Pan 已提交
191
            this.options.onstop();
P
Peter Pan 已提交
192 193 194 195 196 197 198 199
            this.source = null;
        });
        if (this.offset >= this.duration) {
            this.offset = 0;
        }
        this.source.start(0, this.offset);
        this.startAt = this.context.currentTime;
        this.playing = true;
P
Peter Pan 已提交
200
        this.options.onplay();
P
Peter Pan 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    }

    pause() {
        if (!this.buffer) {
            throw new Error('No audio loaded');
        }
        this.source?.stop(0);
    }

    toggle() {
        this.playing ? this.pause() : this.play();
    }

    stop() {
        this.pause();
        this.startAt = 0;
        this.stopAt = 0;
        this.offset = 0;
    }

    seek(offset: number) {
        if (offset != null && (offset < 0 || offset > this.duration)) {
            throw new Error('Invalid offset');
        }
        this.offset = offset;
    }

    toggleMute() {
P
Peter Pan 已提交
229 230
        if (this.volume === 0) {
            this.volume = this.toggleVolume || 100;
P
Peter Pan 已提交
231
        } else {
P
Peter Pan 已提交
232 233
            this.toggleVolume = this.volume;
            this.volume = 0;
P
Peter Pan 已提交
234 235 236 237 238
        }
    }

    dispose() {
        this.reset();
P
Peter Pan 已提交
239 240 241
        if (!this.contextFromOptions) {
            this.context.close();
        }
P
Peter Pan 已提交
242 243 244 245
        this.source = null;
        this.buffer = null;
    }
}