audio.ts 6.2 KB
Newer Older
P
Peter Pan 已提交
1
interface AudioPlayerOptions {
P
Peter Pan 已提交
2 3
    context?: AudioContext;
    volumn?: number;
P
Peter Pan 已提交
4 5 6 7 8 9 10 11 12
    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 已提交
13
    private decodedSampleRate: number = Number.NaN;
P
Peter Pan 已提交
14
    private contextFromOptions: boolean;
P
Peter Pan 已提交
15 16 17 18 19 20 21 22 23

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

    private toggleVolumn = 100;

    public playing = false;

P
Peter Pan 已提交
24
    public readonly options: Required<AudioPlayerOptions>;
P
Peter Pan 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

    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 已提交
44
        return this.decodedSampleRate;
P
Peter Pan 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58
    }

    get volumn() {
        return this.gain.gain.value * 100;
    }
    set volumn(value: number) {
        if (value > 100) {
            value = 100;
        } else if (value < 0) {
            value = 0;
        }
        this.gain.gain.value = value / 100;
    }

P
Peter Pan 已提交
59
    constructor(options?: AudioPlayerOptions) {
P
Peter Pan 已提交
60
        this.options = {
P
Peter Pan 已提交
61
            context: options?.context ?? new AudioContext(),
P
Peter Pan 已提交
62
            volumn: 100,
P
Peter Pan 已提交
63 64
            onplay: () => void 0,
            onstop: () => void 0,
P
Peter Pan 已提交
65 66
            ...options
        };
P
Peter Pan 已提交
67 68
        this.contextFromOptions = !!options?.context;
        this.context = this.options.context;
P
Peter Pan 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        this.gain = this.context.createGain();
        this.volumn = this.options.volumn;
    }

    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 已提交
85 86 87 88 89 90 91 92 93 94 95
    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 已提交
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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    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 已提交
140
    load(buffer: ArrayBuffer, type?: string) {
P
Peter Pan 已提交
141
        this.reset();
P
Peter Pan 已提交
142
        if (type === 'wav') {
P
Peter Pan 已提交
143
            this.decodedSampleRate = AudioPlayer.getWavSampleRate(buffer);
P
Peter Pan 已提交
144 145
        } else if (type === 'mpga' || type === 'mp3') {
            this.decodedSampleRate = AudioPlayer.getMp3SampleRate(buffer);
P
Peter Pan 已提交
146 147 148
        } else {
            this.decodedSampleRate = Number.NaN;
        }
P
Peter Pan 已提交
149 150 151 152 153 154 155 156 157 158
        // 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 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172
        });
    }

    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 已提交
173
            this.options.onstop();
P
Peter Pan 已提交
174 175 176 177 178 179 180 181
            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 已提交
182
        this.options.onplay();
P
Peter Pan 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    }

    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() {
        if (this.volumn === 0) {
            this.volumn = this.toggleVolumn || 100;
        } else {
            this.toggleVolumn = this.volumn;
            this.volumn = 0;
        }
    }

    dispose() {
        this.reset();
P
Peter Pan 已提交
221 222 223
        if (!this.contextFromOptions) {
            this.context.close();
        }
P
Peter Pan 已提交
224 225 226 227
        this.source = null;
        this.buffer = null;
    }
}