JavaScript示波器无法正常工作/音频播放问题

时间:2019-01-31 07:59:21

标签: javascript audio

我是JS的新手。我在https://github.com/mathiasvr/audio-oscilloscope找到了这个示波器示例,这看起来很简单,但是我无法播放音频。 HTML5音频元素显示在浏览器中,它会加载音频,但是当我按play时,什么也没有发生。另外,示波器的画布似乎在那里,但这很难分辨,因为没有音频输入。

我认为问题与npm安装有关,因为在尝试将其安装到目录时在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(?)内创建图形,并且这也阻止了音频播放(?)

HTML中的这一行<script src="../dist/oscilloscope.min.js">也很重要,因为Git下载文件中没有该目录。该可选脚本中的URL显然指向具有该特定目录的该特定文件

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

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

此外,为了解决“ HTML相关行”,我去了//unpkg.com/oscilloscope@1.1.0/dist/oscilloscope.min.js,然后将其复制/粘贴到txt编辑器中,创建了请求的目录/文件。示波器的行出现了,但是音频仍然无法播放...尽管脚本没有格式化,但我也从底部开始包含了脚本,因此我将其放置在“美化器”中。由于是新的,我不确定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

1 个答案:

答案 0 :(得分:0)

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

file://协议不适用于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