基本上,我已经使用 MediaDevices.getUserMedia WebRTC API 设置了一个应用程序。我已经录制了音频,理论上一切都很好。但我现在必须检索音频来听他们的声音。
我现在想知道如何在我的 MongoDB 数据库中下载音频帖子。我尝试导出 MongoDB 数据库,但只收到 JSON 或 CSV 文件,而不是音频文件。
我听说过 gridFS,但仅限于图像处理上下文。在深入研究 gridFS 之前,我想了解一下您对使用 Mlab 进行音频检索的想法。以及更广泛的 MongoDB。
另外,gridFS 似乎是为大文件设计的,但就我而言,我只想存储数百字节的小文件,所以 gridFS 似乎有点过头了?也许有更有效的解决方案?
编辑:我很难翻译我的数据以便将其存储在我的数据库中。
到目前为止,我的控制台返回了我:
XML Parsing Error: syntax error
这是我的 App.js :
// post section
async handleSubmit(e){
e.preventDefault();
Axios.post("/api/words",{
"sound":this.state.blob
})
//.then((res) => res.json())
.then((data) => console.log(data))
//pass submitted value to true in order to declench allDelete function
}
(...)
// blob formatting section :
saveAudio() {
// convert saved chunks to blob
const blob = new Blob(this.chunks, {type: audioType});
this.setState({blob : blob})
Thanks.
对于小于 16 MB 的文件,不需要 GridFS。您可以使用以下方法直接将二进制数据存储在 MongoDB 中BSON的二进制类型或对二进制数据进行编码并将其存储为字符串。将二进制数据存储为字符串时,Base64 是常见的编码选择。
从数据库中检索数据后,可以使用以下命令将其写入文件fs.writeFile.
如果您将数据保存为二进制类型,则可以传递buffer to fs.writeFile
。如果您将数据保存为编码字符串,则可以传递一个字符串和一个encoding
选项。
(如果您想使用 Express 提供文件,您可以设置内容类型并使用res.send)
这是 NodeJS 中的一个小例子。这将从磁盘读取音频文件,将其作为二进制类型保存到 MongoDB 数据库(使用 MongoDB 驱动程序的Binaryclass),从数据库检索它,并将其写入磁盘上的新文件。
const mongodb = require('mongodb')
const util = require('util')
const fs = require('fs')
const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)
async function main() {
const client = await mongodb.MongoClient.connect(process.env.MONGO_URI)
console.log('connected')
let db = await client.db('dbname')
// Reading in binary data from a file. data is a buffer.
let data = await readFile(__dirname + '/sample.mp3')
// Insert binary data to the database
let res = await db.collection('coll').insert({data: new mongodb.Binary(data)})
console.log(res)
let objectId = res.ops[0]._id
// Retrieve binary data from the database
let obj = await db.collection('coll').findOne({_id: objectId})
console.log(obj)
// *** This is the key part ***
// use obj.data.read to get a buffer from the binary data and write that buffer to a file
await writeFile(__dirname + '/out.mp3', obj.data.read(0, obj.data.length()))
console.log('done')
}
main()
尽管人们确实将二进制数据存储在数据库中,但人们最常见的可能是将文件存储在文件系统或对象存储(例如 Amazon S3)中。然后,他们只需在数据库中存储该文件的链接,并使用该链接检索该文件。您可以做任何您觉得更舒服的事情。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)