简体   繁体   English

在电子中打开本地文件并在wavesurfer.js中渲染

[英]Open local file in electron and render in wavesurfer.js

I'm working on an app built with electron, it should work with wavesurfer.js to display a waveform representing the audio file. 我正在开发一个用电子构建的应用程序,它应该与wavesurfer.js一起显示表示音频文件的波形。 However, I'm having trouble opening the file using the fs module and pushing the file content to wavesurfer via a Blob. 但是,我无法使用fs模块打开文件,并通过Blob将文件内容推送到waveurfer。 The file loads and everything seems to work but when decoding wavesurfer says Error decoding audiobuffer . 文件加载,一切似乎都工作,但解码waveurfer说Error decoding audiobuffer

Two things I thought maybe could influence this: 我认为可能有两件事可能影响到这一点:

  • The fs.readFile function takes an encoding as second parameter fs.readFile函数将编码作为第二个参数
  • The Blob constructor takes an options object as second parameter, whithin this you can define the mimetype via the type property Blob构造函数将选项对象作为第二个参数,在此您可以通过type属性定义mimetype

However, until now both approaches have failed to fix the problem. 但是,到目前为止,这两种方法都无法解决问题。

I hope somebody has a solution. 我希望有人有解决方案。 (Could also be the fs.readFile function is entirely the wrong way to go and there's a much better way; I'm just looking for a relatively performant way of opening a file, any help is appreciated) Cheers! (也可能是fs.readFile函数完全是错误的方式,并且有一个更好的方法;我只是在寻找一种相对fs.readFile的打开文件的方式,感谢任何帮助)干杯!

Here's the code … 这是代码......

(I'm leaving out all the electron boilerplate, you can get it easily by doing git clone https://github.com/sindresorhus/electron-boilerplate/ ) – Include a script tag to main.js in the index.html , add a div with the id wave-area somewhere in the html and add a script tag to the the wavesurfer.js library . (我要省略所有的电子样板,你可以通过git clone https://github.com/sindresorhus/electron-boilerplate/轻松搞定) - 在index.html包含一个脚本标签到main.js ,在html中的某处添加一个id为wave-area的div,并将一个脚本标记添加到wavesurfer.js库中 Also you will need a local copy of the demo wav-file . 您还需要演示wav文件的本地副本。

Then in the main.js file … 然后在main.js文件中...

var fs = require('fs');

var wavesurfer = Object.create(WaveSurfer);
wavesurfer.init({
  container: '#wave-area'
});

fs.readFile('/path/to/demo.wav', function(err, data) {
  if (data && !err) {
    console.log('has data and no error!');
  }
  var file = new window.Blob([data]);
  wavesurfer.loadBlob(file);
}

wavesurfer.on('loading', function(e) {
  console.log('loading', e);
});

wavesurfer.on('error', function(err) {
  console.log(err);
});

I finally found the solution! 我终于找到了解决方案! The blob which is passed to wavesurfer through the loadBlob method needs to transformed into an Uint8Array 通过loadBlob方法传递给waveurfer的blob需要转换为Uint8Array

The working code looks like this 工作代码看起来像这样

fs.readFile('/path/to/demo.wav', function(err, buffer) {
  // …
  var blob = new window.Blob([new Uint8Array(buffer)]);
  wavesurfer.loadBlob(blob);
}

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

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