Akxe
Akxe

Reputation: 11565

How to seek with AudioContext

I would like to create buttons that will play next/prev song on click, but they should seek the music on long press.

I did manage to change songs, but I couldn't find the seek methods. Also how to make it play from beginning?

And is there a way to determine how much have passed since the beginning of the song? I found that buffer have duration, but no sing of actual play time.

At init:

context = new (window.AudioContext || window.webkitAudioContext)()

To play song:

var buffer = song.buffer
var source = context.createBufferSource()
source.buffer = song.buffer
source.connect(analysers.main)
source.start(0, offset || 0)

Upvotes: 13

Views: 6579

Answers (2)

Dmitry Volokh
Dmitry Volokh

Reputation: 1646

Guess, you should use AudioBufferNode (it has ability to do seek) - https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/start

Also, this wrapper might be usefull - https://github.com/eipark/buffaudio

Upvotes: 3

Dharani Dharan
Dharani Dharan

Reputation: 644

Use taphold API to acheive the long press Event.

$(function(){
  $( "your element" ).bind( "taphold", tapholdHandler );

  function tapholdHandler( event ){
   /*write your code here for seek forward */

  }
});

Use JQuery Timer

var mousedowntime;
    var presstime;
    $("button[id$='" + buttonID + "']").mousedown(function() {
        var d = new Date();
        mousedowntime = d.getTime();
    });
    $("button[id$='" + buttonID + "']").mouseup(function() {
        var d = new Date();
        presstime = d.getTime() - mousedowntime;
        if (presstime > 999/*You can decide the time*/) {
            //Do_Action_Long_Press_Event();
        }
        else {
            //Do_Action_Click_Event();
        }
    });

To Play from Beginning

function beginAudio(){
            audio.trigger('pause');
            audio.prop("currentTime",audio.prop("currentTime")-audio.prop("currentTime"));
            audio.trigger('play');
        }

or set current time to zero and then play.

For Forward and Backward use this

audio.prop("currentTime",audio.prop("currentTime")-5);// 5 secs backward
audio.prop("currentTime",audio.prop("currentTime")+5);// 5 secs forward

Upvotes: 1

Related Questions