我已将音频、图像和视频文件上传到 Google Cloud Storage (GCS)。虽然我可以在设备上成功下载和查看图像和视频,但在播放音频文件时遇到问题。
音频文件以 MP3 文件类型存储。我发现可以通过将音频文件的文件扩展名更改为 webm 来解决此问题。但是,这个解决方案并不理想,因为每次要重播音频时都需要打开浏览器,这会破坏用户体验。
代码:
const storage = getStorage();
let file = post.fileUrl;
getDownloadURL(ref(storage, file))
.then((url) => {
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = (event) => {
const blob = xhr.response;
//create a file from the returned blob
var file = new File(
[blob],
'file'
,
{
type: blob.type,
},
);
//create anchor tag
var link = document.createElement('a');
//set the download attribute of the a tag to the name stored in the file
link.download = file.name;
//generate a temp url to host the file for download
link.href = URL.createObjectURL(file);
link.click();
};
xhr.open('GET', url);
xhr.send();
})
.catch((err) => {
console.log(err);})
我尝试将文件设置为 mp3,因为对于音频,它会下载 xml 文件。
var file = new File(
[blob],
`${dataHandle}_GoodbyeApp
${
post.fileType === 'audio'
? '.mp3'
: ''
}`,
{
type: blob.type,
},
);
现在它总是下载一个无法播放的mp3文件。 有什么想法可以使用 MP3 吗?
发布我的评论作为答案:
从 GCS 下载 MP3 文件时,请确保服务器响应时将正确的“Content-Type”标头设置为“audio/mpeg”。这告知浏览器下载的数据确实是 MP3 音频文件。