const audioContext: AudioContext = new AudioContext();
const gainNode: GainNode = audioContext.createGain();
gainNode.connect(audioContext.destination);
let currentSource: AudioBufferSourceNode | null = null;
const play = async (arrayBuffer: ArrayBuffer, offset: number = 0): Promise<void> => {
if (currentSource) {
currentSource.onended = null;
currentSource.stop(0);
currentSource.disconnect();
}
const source = audioContext.createBufferSource();
source.connect(gainNode);
currentSource = source;
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
source.buffer = audioBuffer;
source.start(audioContext.currentTime, offset);
}
const pause = async (): Promise<boolean> => {
await audioContext.suspend();
return true;
}
const restart = async (): Promise<boolean> => {
await audioContext.resume();
return true;
}
const setVolume = (value: number): void => {
gainNode.gain.value = value;
}
fetch('xxx.mp3')
.then(res => res.arrayBuffer())
.then(play);
type ImageConvert = (
img: HTMLImageElement | HTMLCanvasElement | string,
download?: boolean,
width?: number,
height?: number,
) => Promise<string>;
const imageConvert: ImageConvert = async (img, download, width, height) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const image = new Image();
image.crossOrigin = 'anonymous';
if (img instanceof HTMLImageElement) {
image.src = img.src;
} else if (img instanceof HTMLCanvasElement) {
image.src = img.toDataURL('image/png');
} else {
image.src = img;
}
await new Promise<any>(resolve => {
image.onload = resolve;
});
const targetWidth = width || image.width;
const targetHeight = height || image.height;
canvas.width = targetWidth;
canvas.height = targetHeight;
ctx.drawImage(image, 0, 0, targetWidth, targetHeight);
const base64Data = canvas.toDataURL('image/png');
if (download) {
const a = document.createElement('a');
a.href = base64Data;
const fileName = typeof download === 'string' ? download : 'image';
a.download = `${fileName}.png`;
a.click();
}
return base64Data;
}