<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>播放语音的demo</title>
</head>
<body>
<div class="lib-audio-main">点击播放语音</div>
<!--设置一个清除语音的标签-->
<div class="audio-container" style="display: none !important;"></div>
</body>
</html>
<script>
var audioContainer = $('.audio-container');
/* 点击播放 */
$(document).on('click', '.lib-audio-main',
function() {
var icon = $(this).find('.lib-click-listen');
var isPlayed = icon.hasClass('playing-audio');
// 停止其他记录音频播放
stopAudio();
// 如果已经播放则return 不继续操作
if (isPlayed) return;
//获取音频的资源路径
var url = icon.attr('data-audio-source');
//添加播放是的演示 移除停止的样式
icon.addClass('playing-audio').removeClass('stop-playing');
//调用方法播放音频
createAudioElement(url);
});
// 重新创建 audio 标签来播放选择的音频
function createAudioElement(src) {
//使用audio标签 来播放我们想要播放的音频
var audioElement = $('<audio src="' + src + '"></audio>');
$('.audio-container').empty().append(audioElement);
audioElement[0].play();
//音频结束停止播放
audioElement[0].addEventListener('ended',
function() {
stopAudio();
});
}
// 音频视图全部设为静态
function stopAudio() {
// 清掉 audio 标签
var audioElement = audioContainer.children('audio');
if (audioElement.length !== 0) {
audioElement[0].pause();
audioContainer.empty();
}
var playingHistory = $('.lib-click-listen.playing-audio');
playingHistory.removeClass('playing-audio').addClass('stop-playing');
// 会话框内记录
var playingRecord = $('.audio-content.playing-audio');
playingRecord.removeClass('playing-audio');
// 被解答语音
var explainAudioTarget = $('.explain-audio-target.playing-audio');
explainAudioTarget.removeClass('playing-audio');
}
</script>
使用h5 <audio>标签播放语音
最新推荐文章于 2024-10-11 21:36:21 发布