Question

With the help of waveformjs.org I am able to draw waveform for a mp3 file. I can also use wav2json to get json data for audio file hosted on my own server and I don't have to depend on soundcloud for that. So far so good. Now, the next challenges for me are

  1. To fill the color in waveform as the audio playing progresses.
  2. On clicking anywhere on waveform audio should start playing from that point.

Has anyone done similar? I tried to look into soundcloud js SDK but no success. Any pointers in this directions will be appreciated, thanks.

Was it helpful?

Solution

As to changing the color my earlier answer here may help:
Soundcloud modify the waveform color

As to moving the position when you click on the waveform you can do something like this:

Assuming you have a x position already from the click event adjusted relative to the canvas.

/// get a representation of x relative to what the waveform represents:
var pos = (x - waveFormX) / waveformWidth;

/// To convert this to time, simply multiply this factor with duration which
/// is in seconds:
audio.currentTime = audio.duration * pos;

Hope this helps!

Update

The requestAnimationFrame is optimized not only for performance but also power consumption as more and more users are on mobile devices. For this reason the browsers may or may not pause or reduce frame rate of rAF when in a different tab or when browser tab is invisible. This can cause a position based approach to render the waveform delayed or not at all when tab is switched.

I would recommend to always use a time based approach so neither FPS or other behavior will interrupt the drawing of the waveform.

You can force the waveform to be updated at the actual current time as luckily we can attach this to the currentTime property of the audio element.

In the rAF loop simply update the position like this using a "reversed" formula of the above:

pos = audio.currentTime / audio.duration * waveformWidth + waveformX

When the tab becomes visible again this approach will make sure the waveform continues based on the actual time position of the audio.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top