Shazije Mustabelli
Shazije Mustabelli

Reputation: 53

play audio from x to y seconds

I'm trying to play an audio file from a second x to a second y. I'll try to explain it in a better way.

I have a text and I want an audio file to play when I click on a word. The point is that I don't want to play the whole audio file but just the piece of audio that says the clicked word. I would like to use a single audio file with all the words of my text (not a single audio file for each word) and extract the part of the audio where the word is said.

At the moment I have the audio file and for each word I know the exact second when it begins and when it ends.

Example:

My text is: "Hi everyone how are you? I'm good." When I click on "everyone" I want to get the piece of audio when it says "everyone".

JAVASCRIPT:

<script src="jquery-1.11.1.min.js"></script>
<script>

$(document).ready(function() {
    $('#1').click(function (){
            //play audiofile from 0 sec to 1 sec
        });
    $('#2').click(function (){
            //play audiofile from 1 sec to 2 sec
        });
    $('#3').click(function (){
            //play audiofile from 2 sec to 3 sec
        });
    $('#4').click(function (){
            //play audiofile from 3 sec to 4 sec
        });

});
</script>

HTML:

<body>

<div><span id="1">Hello </span><span id="2">World! </span><span id="3">Life </span><span id="4">long</span></div>

</body>

I already used functions .play() and .pause() but they are not good for me because I want to get words randomly.

Thank you in advance!

Upvotes: 2

Views: 2406

Answers (2)

Alex
Alex

Reputation: 10216

Add a data-word to each element with a class 'word':

<p>
  <span class="word" data-word="hello" id="1">Hello </span><span class="word" data-word="world" id="2">World! </span><span class="word" data-word="life" id="3">Life </span><span class="word" data-word="long" id="4">long</span>
</p>

Then in your jQuery write:

(function($) {
  $(function() {
    var audio = $('audio').get(0),
      word_timings = {
        'hello': {start: 0, end: 1},
        'world': {start: 1, end: 2},
        'life': {start: 2, end: 3},
        'long': {start: 4, end: 4}
      };

    $('.word').click(function() {
      var word = $(this).data('word'),
        start = word_timings[word].start,
        end = word_timings[word].end;

      audio.pause().currentTime = start;
      audio.play();
      $(audio).on('timeupdate', function() {
        if (this.currentTime >= end) {
          this.pause();
          $(audio).off('timeupdate');
        }
      });

    });
  });
})(jQuery);

In the array word_timings you can then define which word starts and ends at what second/time.

Upvotes: 2

Man Programmer
Man Programmer

Reputation: 5356

try:

function dynamicVoice(text){
  var msg = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(msg);
  }

dynamicVoice("Hello World");
`

browser api for text to voice

Upvotes: 0

Related Questions