1

I have a number of mp3 sounds (i, y, e etc.). I would like to play them in a sequence (i.e. without any pauses between them) when user pressed the button based on the word given by user in the text field (for ex., eye).

I know that audio could be played with usage of the following HTML:

<source type="audio/mpeg" id="mp3"></source>

but looks like this is different from what I need.

LA_
  • 19,823
  • 58
  • 172
  • 308

1 Answers1

1

You could use the ended event to play the next sound when the previous sound completes:

var i = document.getElementById("i"),
    y = document.getElementById("y"),
    e = document.getElementById("e");
i.addEventListener("ended", function() {
  y.play();
}, false);
y.addEventListener("ended", function() {
  e.play();
}, false);
i.play();
<audio id="i" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_unrounded_vowel.mp3"  controls></audio>

<audio id="y" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_rounded_vowel.mp3" controls></audio>

<audio id="e" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close-mid_front_unrounded_vowel.mp3" controls></audio>

...but note that those audio files have pauses in the audio data. So you'll either have to edit the files, or have to set the audio position on them, probably a custom value for each sound, and you'll have to respond to the timeupdate event instead, watching for the point within the audio where you believe the sound actually ends, stopping playback at that point and starting the next one.

Here's an example chopping off the first and last parts of the i sound:

var i = document.getElementById("i"),
    y = document.getElementById("y"),
    e = document.getElementById("e");
var istarted = false, istop;
i.addEventListener("canplay", function() {
  this.currentTime = 0.02;
  istop = this.duration - 0.6;
  if (!istarted) {
    this.play();
    istarted = true;
  }
});
i.addEventListener("timeupdate", function() {
  if (this.currentTime > istop) {
    this.pause();
    y.play();
  }
}, false);
y.addEventListener("ended", function() {
  e.play();
}, false);
<audio id="i" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_unrounded_vowel.mp3"  controls></audio>

<audio id="y" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close_front_rounded_vowel.mp3" controls></audio>

<audio id="e" src="http://www.internationalphoneticalphabet.org/ipa-sounds-folder/mp3/Close-mid_front_unrounded_vowel.mp3" controls></audio>

Neither of the above is very robust, should probably be waiting to make sure the media is loaded, etc. They're just to point to the relevant things to do.

Also note that timeupdate is a bit of a "best effort" event, it's not going to be hyper-precise.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875