Изменение значения переменной Javascript с помощью HTML-элемента при нажатии (wavesurfer.js) - PullRequest
2 голосов
/ 04 октября 2019

Я использую Wavesurfer.js для визуализации сигналов от. Есть ли способ использовать jQuery или Javascript для динамического изменения загруженного аудиофайла при нажатии на элемент HTML?

Я могу визуализировать отдельный файл, но не знаю, как динамически изменить загруженный файл.

Вот экземпляр Wavesurfer.js в моем нижнем колонтитуле

<script>

var wavesurfer = WaveSurfer.create({
  backend: 'MediaElement',
    container: '#waveform',
    barWidth: 1,
    barGap: 3,
    cursorColor: '#e15a13',
    cursorWidth: 3,
    mediaControls: true,
    hideScrollbar: true,
    waveColor: "#000000",
    fillParent: true,
    responsive: true,
});

wavesurfer.setHeight(40);
wavesurfer.load('http://dev.chrislamdesign.com/shortwave/wp-content/uploads/2019/10/Pharrell-Williams-Happy-Official-Music-Video-1.mp3');

wavesurfer.on('ready', updateTimer)
wavesurfer.on('audioprocess', updateTimer)

// Need to watch for seek in addition to audioprocess as audioprocess doesn't fire
// if the audio is paused.
wavesurfer.on('seek', updateTimer)

function updateTimer() {
  var formattedTime = secondsToTimestamp(wavesurfer.getCurrentTime());
  $('.waveform-time-indicator .time').text(formattedTime);
}

function secondsToTimestamp(seconds) {
  seconds = Math.floor(seconds);
  var h = Math.floor(seconds / 3600);
  var m = Math.floor((seconds - (h * 3600)) / 60);
  var s = seconds - (h * 3600) - (m * 60);

  h = h < 10 ? '0' + h : h;
  m = m < 10 ? '0' + m : m;
  s = s < 10 ? '0' + s : s;
  return h + ':' + m + ':' + s;
}
</script>

Я хочу заменить загруженный файл (wavesurfer.load) HTML-строкой при нажатии. Я использую Wordpress для зацикливания результатов песни, каждый из которых имеет URL-адрес, напечатанный в теге абзаца с классом «move_to_wavesurfer». Поэтому, когда я нажимаю на песню, я хочу заменить значение wavesurfer.load значением тега абзаца.

Вот HTML-код для вставки

<div class="col-md-3">
<a class="song-link" data-target="#song-8">
    <img width="606" height="610" src="http://dev.chrislamdesign.com/shortwave/wp-content/uploads/2019/07/cover.png" class="attachment-full size-full wp-post-image" alt="" srcset="http://dev.chrislamdesign.com/shortwave/wp-content/uploads/2019/07/cover.png 606w, http://dev.chrislamdesign.com/shortwave/wp-content/uploads/2019/07/cover-150x150.png 150w, http://dev.chrislamdesign.com/shortwave/wp-content/uploads/2019/07/cover-298x300.png 298w" sizes="(max-width: 606px) 100vw, 606px"></a>

<p class="move_to_wavesurfer>http://dev.chrislamdesign.com/shortwave/wp-content/uploads/2019/10/other_song.mp3</p>

</div>
        </div>

1 Ответ

1 голос
/ 04 октября 2019
<p>In your PHP loop... maybe you can put the urls in a data attribute</p>

<button rel='song-switch' data-song-url='song-url-a'>
  play
</button>

<button rel='song-switch' data-song-url='other-song-url'>
  play
</button>

...

console.clear();
// I'd normally write this in plain JavaScript - but since you are using WordPress - it has jQuery already

function switchTrack(url) {
    // your code...
  alert('play the song ' + url);
}

// get references to the HTML(DOM) elements
var $switches = $('[rel="song-switch"]');

// add event listeners to each switch
$switches.each( function() {
  // $(this) refers to each switch
  $(this).on('click', function() {
    var url = $(this).data('song-url'); // get the value of that attr
        //
    switchTrack(url); // pass it into your function - to load a new track
    // and this is where you'd work with the player's api...
    // consider wrapping your current code in a function - or breaking it into some reusable functions
  });
});

// yes... you should use event delegation... but you can look that up in the future.

Из того, что я вижу в вашем коде - у вас, вероятно, нет файла сценария / или вы его не используете - поэтому не забудьте поставить этоJS в теге скрипта / или вообще - просто убедитесь, что он в нужном вам месте.

Здесь вы можете узнать больше о jQuery и всех его функциях: https://jquery.com/

https://jsfiddle.net/sheriffderek/teLm7drn

а также ... имейте в виду, что с WordPress ... вам нужно обернуть свой код jQuery примерно так:

(function($) {
  // $ Works! You can test it with next line if you like
  // console.log($);
})( jQuery );
...