简体   繁体   中英

custom start and end points for html audio element

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. Ie 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, ie 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

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.

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)
    });

我会修剪.wav文件本身

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM