example
All you have to is to write below html code:
a span with class name of word-audio
and attribute of data-src
pointed to a audio stream resource
<span class='word-audio audio' style='display:inline-block' data-src='https://cdn.mp3xa.pw/proxy/cs1-43v4.vkuseraudio.net/p17/fe6d95af2cee33.mp3'></span>
Bertie Higgins — Casablanca
word.js
function startAnimation(e) {
if (e.className == 'word-audio audio')
e.className = 'word-audio audio-light';
else if (e.className == 'word-audio audio-light')
e.className = 'word-audio audio-playing';
else
e.className = 'word-audio audio'
console.log(e.className);
}
function play(e, context, audioBuffer) {
if (e.state == 1) {
e.source.stop();
e.source.onended();
e.source = null;
e.state = 0;
} else {
e.state = 1;
const source = context.createBufferSource();
e.source = source;
source.buffer = audioBuffer;
source.connect(context.destination);
source.start();
let it = setInterval(function() {startAnimation(e)}, 300);
source.onended = function() {
clearInterval(it);
e.className = 'word-audio audio';
}
}
}
document.querySelectorAll('.word-audio').forEach(function(e, index) {
let url = e.attributes['data-src'].nodeValue;
let context = new AudioContext();
e.state = 0;
let wordBuffer;
window.fetch(url)
.then(response => response.arrayBuffer())
.then(arrayBuffer => context.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
e.disabled = false;
wordBuffer = audioBuffer;
//play(e, context, wordBuffer);
});
e.onclick = function() {
play(e, context, wordBuffer);
}
});
word.css
.audio {
display: inline-block;
width: 20px;
height: 20px;
position: relative;
overflow: hidden;
cursor: pointer;
vertical-align: middle;
background: url(https://res.hjfile.cn/tool/dict.hjenglish.com/img/audio-dark-ea178.png) no-repeat -40px 0/auto 100%;
}
.audio-playing {
display: inline-block;
width: 20px;
height: 20px;
position: relative;
overflow: hidden;
cursor: pointer;
vertical-align: middle;
background: url(https://res.hjfile.cn/tool/dict.hjenglish.com/img/audio-dark-ea178.png) no-repeat -20px 0/auto 100%;
}
.audio-light {
display: inline-block;
width: 20px;
height: 20px;
position: relative;
overflow: hidden;
cursor: pointer;
vertical-align: middle;
background: url(https://res.hjfile.cn/tool/dict.hjenglish.com/img/audio-dark-ea178.png) no-repeat 0px 0/auto 100%;
}