3

I have a html audio element playing my track. It's a pretty simple setup:

<audio controls loop="loop">
    <source type="audio/wav" src="song.wav">
</audio>

I thought it would be just as simple to make custom start and end points. I.e. if my track is 10 seconds long, I want to trim a little so only the middle of the song is played.

From the W3 audio tag doc it doesn't seem like there's any options for specifying a start and end time.

I'm not asking for anyone to write code for me; I'm looking for a conceptual guide for how to approach this. I need it to work with the loop, i.e. it should start and end at my specified values every loop. I'm looking for an approach that is totally client side and that works in Chrome

max pleaner
  • 26,189
  • 9
  • 66
  • 118

3 Answers3

1

I did figure out something that works.

The canplaythrough event won't suffice because the audio will be looping; this event is only fired once

As an alternative, I'm using the timeupdate event: (this in coffeescript)

   window.playbackStart = 2
   window.playbackEnd = 4

   $("audio").off("timeupdate").on "timeupdate", (e) ->
      audio = e.currentTarget
      if audio.currentTime > playbackEnd
        audio.currentTime = playbackStart

this seems simple enough, but I had to do a little debugging because calling currentTime = was not working (it was just setting the time to zero, no matter what). It turns out the issue was actually server-side (see https://stackoverflow.com/a/32667819/2981429).

I needed to:

  1. Configure my server to use HTTP 1.1

    • with Nginx, I added

      proxy_http_version 1.1;
      proxy_set_header Connection "";
      

      to my location { } block

  2. In my application, set the header Accept-Ranges: bytes with the response.
Community
  • 1
  • 1
max pleaner
  • 26,189
  • 9
  • 66
  • 118
0

This is slightly altered code from the answer i linked to in the comments... see commments for info

http://jsfiddle.net/mNPCP/313/

// set start and end times 
    var startTime = 12;
    var endTime = 15;
    myAudio=document.getElementById('audio2');
    myAudio.addEventListener('canplaythrough', function() {

      // start it at the start time
      this.currentTime = startTime;
      this.play();
      // let it play to the end time and then reset the play time
      setTimeout(function(){
        this.currentTime = startTime;
      }, (endTime-startTime)*1000)
    });
Robert Parham
  • 704
  • 3
  • 10
  • unfortunately i don't think it will be this simple. Chrome has issues with setting currentTime and `canplaythough` won't suffice when the audio is looping. Though I appreciate your attempt. I'll let you know what I figure out – max pleaner Sep 06 '16 at 21:23
  • after a little more research, it seems my problem may actually be server side (see http://stackoverflow.com/a/32667819/2981429) – max pleaner Sep 06 '16 at 21:33
-2

I would trim the .wav file itself

becker33
  • 1
  • 1