JavaScript 示波器不工作/音频播放问题

标签 javascript audio

我是 JS 新手。我在 https://github.com/mathiasvr/audio-oscilloscope 找到了这个示波器示例看起来很简单,但我无法播放音频。 HTML5 音频元素显示在浏览器中,它加载音频,但是当我按下播放时没有任何 react 。此外,示波器的 Canvas 似乎在那里,但这很难说,因为没有音频输入。

我相信这个问题与 npm install 有关,因为我在尝试将它安装到目录时在我的 cmd 中收到此错误消息。

npm ERR! code ENOSELF

npm ERR! Refusing to install package with name "oscilloscope" under a 
package also called"oscilloscope".

Did you name your project the same at the dependency you're installing?

我已经更改了目录的名称,但报告了相同的错误消息。

此外,可以选择在 HTML 中插入这行脚本,但这也不起作用......
<script src="//unpkg.com/oscilloscope@1.1.0/dist/oscilloscope.min.js"> 
</script>

所以我相信它与这个错误有关,因为据我所知,在 Canvas 内创建图形需要节点(?)这也阻止了音频播放(?)

此行<script src="../dist/oscilloscope.min.js"> HTML 中的内容也很重要,因为 Git 下载文件中不存在该目录。并且该可选脚本中的 URL 清楚地指向具有此特定目录的特定文件

我一直在逐行尝试找出 JS 中实际发生的情况。感觉就像某处有一些简单的断开连接。我尝试在 JS 中插入“audioElement.play()”,但这不起作用。

我已经尝试过 mp3 和 wav 文件...

另外,为了解决“关于 HTML 的行”,我去了//unpkg.com/oscilloscope@1.1.0/dist/oscilloscope.min.js 并将其复制/粘贴到 txt 编辑器中,创建了请求的目录/文件.示波器的线出现了,但音频仍然无法播放......我已经在最底部包含了来自那里的脚本,虽然它没有格式化,所以我把它通过一个“美化器”。由于 new 我不确定 JS 的正确格式是什么。

任何方向表示赞赏
<html>
<head>
  <title>Oscilloscope</title>
  <style>
    body {
      margin: 0;
      background-color: #1a1a1a;
      color: #dddddd;
    }
    canvas {
      display: block;
    }
  </style>
<!-- this script or npm -->
<!-- <script src="//unpkg.com/oscilloscope@1.1.0/dist/oscilloscope.min.js"></script> -->
</head>
<body>
  <script src="../dist/oscilloscope.min.js"></script>
  <!-- Examples -->
  <!-- <script src="microphone.js"></script> -->
  <script src="audio-element.js"></script>
  <!-- <script src="custom.js"></script> -->
</body>
</html>

JS
var audioContext = new window.AudioContext()

// setup canvas
var canvas = document.createElement('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight - 50
document.body.appendChild(canvas)

// setup audio element
var audioElement = document.createElement('audio')
audioElement.controls = true
audioElement.autoplay = false
audioElement.src = 'freak.mp3'
audioElement.play()
document.body.appendChild(audioElement)

// create source from html5 audio element
var source = audioContext.createMediaElementSource(audioElement)

// attach oscilloscope
var scope = new Oscilloscope(source)

// reconnect audio output to speakers
source.connect(audioContext.destination)

// customize drawing options
var ctx = canvas.getContext('2d')
ctx.lineWidth = 2
ctx.strokeStyle = '#ffffff'

// start default animation loop
scope.animate(ctx)

JS.min
! function(t, e) {
    "object" == typeof exports && "undefined" != typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : t.Oscilloscope = e()
}(this, function() {
    "use strict";
    var t = function(t, e) {
        if (void 0 === e && (e = {}), !(t instanceof window.AudioNode)) throw new Error("Oscilloscope source must be an AudioNode");
        t instanceof window.AnalyserNode ? this.analyser = t : (this.analyser = t.context.createAnalyser(), t.connect(this.analyser)), e.fftSize && (this.analyser.fftSize = e.fftSize), this.timeDomain = new Uint8Array(this.analyser.frequencyBinCount), this.drawRequest = 0
    };
    return t.prototype.animate = function(t, e, i, n, a) {
        var o = this;
        if (this.drawRequest) throw new Error("Oscilloscope animation is already running");
        this.ctx = t;
        var s = function() {
            t.clearRect(0, 0, t.canvas.width, t.canvas.height), o.draw(t, e, i, n, a), o.drawRequest = window.requestAnimationFrame(s)
        };
        s()
    }, t.prototype.stop = function() {
        this.drawRequest && (window.cancelAnimationFrame(this.drawRequest), this.drawRequest = 0, this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height))
    }, t.prototype.draw = function(t, e, i, n, a) {
        void 0 === e && (e = 0), void 0 === i && (i = 0), void 0 === n && (n = t.canvas.width - e), void 0 === a && (a = t.canvas.height - i), this.analyser.getByteTimeDomainData(this.timeDomain);
        var o = n / this.timeDomain.length;
        t.beginPath();
        for (var s = 0; s < this.timeDomain.length; s += 2) {
            var r = e + s * o,
                c = i + a * (this.timeDomain[s] / 256);
            t.lineTo(r, c)
        }
        t.stroke()
    }, t
});
//# sourceMappingURL=oscilloscope.min.js.map

最佳答案

您无法加载音频文件的原因是因为 CORS,如果您查看控制台,您可能会看到一个名为 Access to audio from origin 'null' has been blocked by CORS policy: 的警告。 .

file://协议(protocol)不适用于 CORS,因此在您的情况下尝试使用本地文件系统访问您的文件不起作用。您可以通过服务器发送文件或通过 FileReader 加载文件来解决此问题。

这是文件阅读器版本的示例。

您需要添加一个接受音频文件的输入标签。

<input id="upload_files" type="file" accept="audio/*">

完成后,您需要将这段 javascript 添加到 osciloscope.main.js 文件中
audioElement.setAttribute("crossorigin", "anonymous");
document.getElementById("upload_files").onchange= function(event)
{
    var reader= new FileReader();
    reader.readAsDataURL(event.target.files[0]);
    reader.onload= function(e)
    {   
        audioElement.setAttribute("src", e.target.result);
        audioElement.play();
    }
};

我还对文件进行了一些其他更改。

HTML
<html>
<head>
  <title>Oscilloscope</title>
  <style>
    body {margin: 0; background-color: #1a1a1a; color: #dddddd;}
    canvas {display: block;}
  </style>
<script src="https://unpkg.com/oscilloscope@1.1.0/dist/oscilloscope.min.js"></script>
</head>
<body>
  <input id="upload_files" type="file" accept="audio/*">
  <script type= "text/javascript" src="../dist/oscilloscope.min.js"></script>
</body>
</html>

JAVASCRIPT
audioElement.setAttribute("crossorigin", "anonymous");
document.getElementById("upload_files").onchange= function(event)
{
    var reader= new FileReader();
    reader.readAsDataURL(event.target.files[0]);
    reader.onload= function(e)
    {   
        audioElement.setAttribute("src", e.target.result);
        audioElement.play();
    }
};

var audioContext = new window.AudioContext();

// setup canvas
var canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight - 50;
document.body.appendChild(canvas);

// setup audio element
var audioElement = document.createElement('audio');
audioElement.controls = true;
document.body.appendChild(audioElement);

// create source from html5 audio element
var source = audioContext.createMediaElementSource(audioElement);

// attach oscilloscope
var scope = new Oscilloscope(source);

// reconnect audio output to speakers
source.connect(audioContext.destination);

// customize drawing options
var ctx = canvas.getContext('2d');
ctx.lineWidth = 2;
ctx.strokeStyle = '#ffffff';

// start default animation loop
scope.animate(ctx);

我实际上有一个普通的 JS,我的 GitHub 上没有音乐播放器的框架版本,如果你有兴趣可以查看。 CLick Here

关于JavaScript 示波器不工作/音频播放问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54455810/

相关文章:

javascript - 如何将字符串解析为对象?

javascript - 有人可以告诉我为什么这个 js 函数不能在加载时运行吗?

javascript - 为什么我从 repl.it 上的这段代码中看到 "Promise { <pending> }"?

ios - 在 GPUImage 中应用视频过滤器时播放音频

ios - 分析语音模式IOS

delphi - 捕捉 Audio Session 事件

javascript - 使用 redux 表单超出更新深度

android - Vitamio Bug播放本地音频

audio - 如何使音频从视频中的指定点和最后指定的时间开始

javascript - JSON从所有网站的所有列表中动态获取两个公告