How do I play a region and “only the region” on wavesurfer.js?

情到浓时终转凉″ 提交于 2021-02-08 10:31:00

问题


I want to play the region specified on the below code; not the whole mp3 file. This will be useful on the project I am currently working on; am build an e-commerce store. I want customers to stream that portion only before they can make a purchase.

//Draws the waveform
var wavesurfer = WaveSurfer.create({
    container       : '#waveform',
    barWidth        : 3,
    barHeight       : 2,
    fillParent      : true,
    hideScrollbar   : true,
    responsive      : true,
    height          : 50,
    waveColor       : '#cccccc',
    progressColor   : '#666666',
    cursorColor     : 'white',
    cursorWidth     : 2,
    //Creates the region I want to play
    plugins: [
        WaveSurfer.regions.create({
            regions: [
                {
                    start: 60,
                    end: 80,
                    loop: false,
                    color: '#cccccc'
                }
            ]
        })
    ]
    
});
//Play and pause buttons
wavesurfer.on('play', function () {
    document.getElementById("playButton").innerHTML = "<i class='material-icons'>pause</i>";
});
wavesurfer.on('pause', function () {
    document.getElementById("playButton").innerHTML = "<i class='material-icons'>play_arrow</i>";
});
//Play and pause function
function togglePlay()
{
    if(wavesurfer.isPlaying())
        wavesurfer.pause();
    else
        wavesurfer.play();
}
//Adds the audio file
var myElement = document.getElementById('my-element');
var myVar = myElement.dataset.myVar;
wavesurfer.load(myVar);
//Hides preloader when waveform is drawn and display the length (duration of the song) 
wavesurfer.on('ready', function () {
    document.getElementById("preloader-cover").style.display = "none";
    var getDuration = wavesurfer.getDuration();
    var min = parseInt(getDuration / 60);
    var sec = (getDuration % 60).toFixed(0);
    var duration = min+":"+sec;
    document.getElementById("length").innerHTML = duration;
});

回答1:


Give an id to your region:

plugins: [
    WaveSurfer.regions.create({
        regions: [
            {
                id: "your id",   
                start: 60,
                end: 80,
                loop: false,
                color: '#cccccc'
            }
        ]
    })
]

And then just call play method on this region:

wavesurfer.regions.list["your id"].play()

This will paly the region from its begining till the "end" of the region. For more doc look at: wavesurfer region plugin doc



来源:https://stackoverflow.com/questions/60503478/how-do-i-play-a-region-and-only-the-region-on-wavesurfer-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!