繁体   English   中英

我想在页面加载时自动从我的代码文件夹中获取一个文件到我的 js 文件中

[英]I want to fetch a file from my code folder to my js file automatically when the page loads

我想在页面加载时自动从我的代码文件夹中获取一个文件到我的 js 文件,以便我可以在音频可视化工具中使用。 我不必从用户计算机上获取它!

我该怎么做? 我试图使用 fetch 来做到这一点,但我现在只能从 URL 中获取。 我想使用这样的文件

    document.getElementById('file').addEventListener('change', function(e){
      this.fileReader.readAsArrayBuffer(e.target.files[0]);
      }.bind(this));
      var _this = this;
    
    this.fileReader.onload = function(){
      _this.audioContext.decodeAudioData(_this.fileReader.result, function(buffer){
        if(_this.source) {
          _this.source.stop();
        }
        _this.source = _this.audioContext.createBufferSource();
        _this.source.buffer = buffer;
        
        _this.source.loop = true;

        _this.source.connect(_this.analyser);

        _this.gainNode = _this.audioContext.createGain();

        _this.source.connect(_this.gainNode);
        _this.gainNode.connect(_this.audioContext.destination);
        _this.source.start(0);
        
        _this.frequencyArray = _this.webgl.sphereG.attributes.aFrequency.array;
        _this.indexPosArray = _this.webgl.indexPosArray;
        _this.indexPosLength = _this.webgl.indexPosArray.length;
        _this.isReady = true;
      });
    };
  }

但不是让用户从他/她的计算机中选择一个文件,我想从我的代码自动所在的文件夹中获取一个文件。

那么不需要<input type="file"/>

你可能会成功

// if the HTML that's executing the current JavaScript is at 
// https://example.com/foo/index.html and audiofile.ext
// is in the same location as index.html (i.e. also inside foo),
// this would work:

fetch('audiofile.ext')
   .then(res => res.blob())
   .then(blob => {
      // do stuff with the blob
   });

请参阅MDN 上fetch 文档

我尝试了你的建议,但它仍然显示一些错误

我在 index.js 中编写的代码

fetch('roses.mp3')
.then(res => res.blob())
.then(blob => {
  console.log(blob);
});

我在控制台中遇到的错误

第一个错误

Fetch API cannot load 
file:///C:/Users/sanid/Desktop/my%20website%20full%20page/roses.mp3. URL scheme must 
be "http" or "https" for CORS request.

第二个错误

index.js:119 Uncaught (in promise) TypeError: Failed to fetch
at index.js:119

我也尝试将源更改为 file:///C:/Users/sanid/Desktop/my%20website%20full%20page/roses.mp3 但它也不起作用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM