0

I'm currently working on a wavesurfer player for my website and this is what i got so far

<html>
<head>
<title>Waveform Player</title>
<script src="wavesurfer.js"></script>
<script>
function hide_player() {
  var x = document.getElementById("player");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
} 
</script>
<style>
html
{
    height: 1500px;
}
</style>
</head>
<body>
<iframe src="http://example.org" height="100%" width="100%"></iframe>

<div style="position: fixed; bottom: 0; right: 0; z-index: 999; display: block; width: 123px; float: right;">
<button onclick="hide_player()">Hide/Show Player</button>
</div>

<div style="position: fixed; z-index: 100; bottom: 0; left: 0; width: 100%; background-color: grey;" id="player">

<div id="waveform"></div>

<table border="0" align="center">
<tr>
<td><button onclick="wavesurfer.skipBackward()"><<</button></td>
<td><button onclick="wavesurfer.playPause()">Play / Pause</button></td>
<td><button onclick="wavesurfer.skipForward()">>></button></td>
<td>Volume:</td>
<td>
<input id="volumeSlider" type="range" name="volume-slider" min="0" max="100" value="50"/>
</td>
<td>
Time:
<span id="currentTime">00:00:00</span>
<span>/</span>
<span id="totalDuration">00:00:00</span>
</td>
</tr>
</table>

</div>
</body>

<script>
//Timecode
const currentTime = document.querySelector("#currentTime")
const totalDuration = document.querySelector("#totalDuration")

//Volume Control
const volumeSlider = document.querySelector("#volumeSlider")

//Load Wavesurfer and options
var wavesurfer = WaveSurfer.create({
    container: '#waveform',
    waveColor: 'violet',
    progressColor: 'blue',
    backgroundColor: 'green',
    responsive: 'true'
});

//Volume Control
const handleVolumeChange = e => {
// Set volume as input value divided by 100
// NB: Wavesurfer only excepts volume value between 0 - 1
const volume = e.target.value / 100

wavesurfer.setVolume(volume)

// Save the value to local storage so it persists between page reloads
localStorage.setItem("audio-player-volume", volume)
}

const setVolumeFromLocalStorage = () => {
// Retrieves the volume from local storage, or falls back to default value of 50
const volume = localStorage.getItem("audio-player-volume") * 100 || 50

volumeSlider.value = volume
}

//Load Track
wavesurfer.load('http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');

//Volume Control
window.addEventListener("load", setVolumeFromLocalStorage)
volumeSlider.addEventListener("input", handleVolumeChange)

//Timecode
const formatTimecode = seconds => {
return new Date(seconds * 1000).toISOString().substr(11, 8)
}

wavesurfer.on("ready", () => {
// Set wavesurfer volume
wavesurfer.setVolume(volumeSlider.value / 100)

// Timecode
const duration = wavesurfer.getDuration()
totalDuration.innerHTML = formatTimecode(duration)
})

wavesurfer.on("audioprocess", () => {
const time = wavesurfer.getCurrentTime()
currentTime.innerHTML = formatTimecode(time)
})

//Spacebar starts player
document.body.onkeyup = function(e){
    if(e.keyCode == 32){
wavesurfer.playPause()
    }
}
window.addEventListener('keydown', function(e) {
  if(e.keyCode == 32 && e.target == document.body) {
    e.preventDefault();
  }
});
</script>
</html>

I tried for hours to implement the cursor plugin:

https://wavesurfer-js.org/example/cursor/index.html
https://wavesurfer-js.org/api/class/src/plugin/cursor/index.js~CursorPlugin.html

But i failed and i'm at the point where i do not know what to do anymore. Can anyone help me out here and edit the code above? I would really appreciate it.

I would also like to have an "active" play / pause button so it says play when the audio is playing and pause if its not. Right now its static and i do not know how to change that.

Lukasz Tracewski
  • 10,794
  • 3
  • 34
  • 53
Michael_
  • 43
  • 8
  • Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Aug 22 '21 at 02:21
  • Checking CSS properties directly is [best avoided](/q/55071684/4642212). Instead, a CSS class should be used, e.g. `.hidden { display: none; }`; then [`.classList.contains("hidden")`](//developer.mozilla.org/docs/Web/API/Element/classList) to check for its existence, `.classList.toggle("hidden")`, etc. Consider using the [`hidden` attribute](//developer.mozilla.org/docs/Web/HTML/Global_attributes/hidden) instead. – Sebastian Simon Aug 22 '21 at 02:22
  • What exactly is failing? Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`) and read any errors. – Sebastian Simon Aug 22 '21 at 02:24

1 Answers1

0

It is not so hard to implement this plugin. You have an example in the documentation.

First load the wavesurfer cursor plugin:

<script src="wavesurfer.cursor.js"></script>

Then you need to add the plugin in the wavesurfer instance:

//Load Wavesurfer and options
var wavesurfer = WaveSurfer.create({
    container: '#waveform',
    waveColor: 'violet',
    progressColor: 'blue',
    backgroundColor: 'green',
    responsive: 'true',
    plugins: [
        WaveSurfer.cursor.create({  // <-- here
            showTime: true,
            opacity: 1,
            customShowTimeStyle: {
                'background-color': '#000',
                color: '#fff',
                padding: '2px',
                'font-size': '10px'
            }
        })
    ]
});

If you want to listen to play and pause events, you can use wavesurfer events listener, as documented here.

wavesurfer.on('pause', function () {
    /* do stuff when wavesurfer is paused */
});

I let you change appearance of the button according to your needs.

TGrif
  • 5,725
  • 9
  • 31
  • 52
  • Where did you get that "wavesurfer.cursor.js" from, man? – Michael_ Aug 24 '21 at 03:47
  • I get it from [cdnjs](https://cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/2.0.4/plugin/wavesurfer.cursor.min.js), but you can find the source on the Github [repo](https://github.com/katspaugh/wavesurfer.js/blob/master/src/plugin/cursor/index.js). – TGrif Aug 24 '21 at 07:47
  • So i copy that github code and name the file "wavesurfer.cursor.js" ? Because its named index.js on github ^^ – Michael_ Aug 25 '21 at 05:07
  • I suggest you get the minified version available on cdn. – TGrif Aug 25 '21 at 08:44