问题描述
您好,这个问题我已经尝试解决了一个多月了,没有任何进展。 我正在尝试在浏览器中录制一些音频,然后将音频上传到谷歌云存储中。这些都很好,我可以录制音频并在谷歌云存储中播放。然而,无论我在下载文件时做了什么,我发现 RIFF 标头已丢失。 例如
'Expected "RIFF" string at 0','Expected "WAVE" string at 4','Expected "fmt " string at 8','UnkNown format: 16904','chunk_size does not match file size'
我存储录制音频的方式是 blob。我的前端是 React,后端是 Nodejs。所以我所做的是将 blob 发送到后端。像下面。并调用 readfile 将数据读入缓冲区
router.post("/audio",upload.any(),async (req,res) => {
const { Storage } = require("@google-cloud/storage");
const storage = new Storage();
const audioBucket = storage.bucket("xxxxxx");
const file = audioBucket.file("audio.wav");
fs.readFile(req.files[0].path,null,(err,data) => {
file.save(data,function (err) {
file.get().then(function (data1) {
console.log(data1);
});
});
}
解决方法
根据官方文档,有几种方法可以向 GCP 发出 upload
请求:
-
Single-request upload
:用于小文件。 -
Resumable upload
:用于大文件的可靠传输。 -
XML API multipart upload
:与 Amazon S3 兼容的上传方法。
我建议您使用 Node.js 的客户端库来上传您的音频。您可以使用 createWriteStream()
方法来做到这一点。以下是有关如何使用此方法的文档提供的示例:
const fs = require('fs');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');
const file = myBucket.file('my-file');
//-
// <h4>Uploading a File</h4>
//
// Now,consider a case where we want to upload a file to your bucket. You
// have the option of using Bucket#upload,but that is just
// a convenience method which will do the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
.pipe(file.createWriteStream())
.on('error',function(err) {})
.on('finish',function() {
// The file upload is complete.
});
//-
// <h4>Uploading a File with gzip compression</h4>
//-
fs.createReadStream('/Users/stephen/site/index.html')
.pipe(file.createWriteStream({ gzip: true }))
.on('error',function() {
// The file upload is complete.
});
//-
// Downloading the file with `createReadStream` will automatically decode
// the file.
//-
//-
// <h4>Uploading a File with Metadata</h4>
//
// One last case you may run into is when you want to upload a file to your
// bucket and set its metadata at the same time. Like above,you can use
// Bucket#upload to do this,which is just a wrapper around
// the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
.pipe(file.createWriteStream({
metadata: {
contentType: 'image/jpeg',metadata: {
custom: 'metadata'
}
}
}))
.on('error',function() {
// The file upload is complete.
});