下列使用.webm音頻文件進行舉例:
文件下載
npm下載file-saver
npm install file-saver
代碼:
import { saveAs } from "file-saver";
async function downloadAudio(src: string, name: string) {
const blob = await getBlob(src);
saveAs(blob, name + ".webm");
}
function getBlob(url: string): Promise<Blob> {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
//或者使用axios
async function getBlob(url: string): Promise<Blob> {
return new Promise(resolve => {
axios.get(url, { responseType: "blob" }).then(resp => resolve(resp.data));
});
}
打包下載
npm install jszip
函數
import JSZip from "jszip";
import { saveAs } from "file-saver";
//data=[{name:xx, ..., src:"blob:xxx"}{...}]
downAllRecord(data: any) {
let zip = new JSZip();//初始化
for (let i = 0; i < data.length; i++) {
let obj = data[i];
zip.file(obj.name + ".webm", getBlob(obj.src));
}
zip.generateAsync({ type: "blob" }).then(function(content: Blob) {
//使用blob下載zip
saveAs(content, "Sound.zip");
//這里也可以寫成使用File下載zip,把blob轉換為File
const filesZip = new File([content], "Sound.zip", { type: "application/zip" });
saveAs(filesZip);
});
}
function getBlob(url: string): Promise<Blob> {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
壓縮包解壓
壓縮包解壓同樣使用的是jszip
const unzipFile = async (url: string) => {
const zipFile = (await axios.get(url, { responseType: "blob" })).data;//以blob形式獲取zip文件
return new Promise<any>(async resolve => {
var zipInit = new JSZip();
const zip = await zipInit.loadAsync(zipFile);//讀取zip文件
const files = zip.files;
let zipFiles = {} as { [id: string]: ArrayBuffer };
const promises = _.map(Object.values(files), async value => {
const audioWavName = value.name;
const audioWav = await value.async("arraybuffer");//以arraybuffer的形式獲得內容(我這里是獲取音頻文件)
zipFiles[audioWavName] = audioWav;
});
await Promise.all(promises);//使用Promise.all等待所有解壓完成
resolve(zipFiles);
});
};