我想在使用ScrollMagic.js进入/离开场景时播放和停止音频。它在Chrome中抛出'Uncaught(in promise)DOMException'。问题是什么?
我有像下面这样的html结构。我想在使用ScrollMagic.js输入每张幻灯片时自动播放音频。
<div class="slide" id="slide-0">
<div class="trigger"></div>
<audio class="audio" src="audio/audio01.mp3" preload="auto"></audio>
</div>
<div class="slide" id="slide-1">
<div class="trigger"></div>
<audio class="audio" src="audio/audio02.mp3" preload="auto"></audio>
</div>
<div class="slide" id="slide-3">
<div class="trigger"></div>
<audio class="audio" src="audio/audio03.mp3" preload="auto"></audio>
</div>
var controller = new ScrollMagic.Controller();
var scenes = [];
$('.slide').each(function(index) {
var trigger = '#slide-' + index + ' .trigger';
var audio = '#slide-' + index + ' audio';
scenes[index] = new ScrollMagic.Scene({
triggerElement: trigger,
triggerHook: 'onCenter',
duration: '50%' })
.addIndicators({name: trigger, colorEnd: "#00FFFF"})
.on('enter', function() {
console.log('Enter' + trigger);
$(audio).get(0).play();})
.on('leave', function() {
console.log('Leave' + trigger); })
.addTo(controller);
});
触发器激活后,控制台在Chrome中显示“Uncaught(in promise)DOMException”。我尝试过Edge,没关系。我怎样才能解决这个问题?
你有正确的想法,因为每个div在理论上都具有相同音频元素的相同索引。只需使用div循环的索引来代替播放音频元素。
例:
let scenes = [];
// init controller
var controller = new ScrollMagic.Controller();
$('.slide').each(function(index) {
var trigger = '#slide-' + index + ' .trigger';
var audio = '#slide-' + index + ' audio';
scenes[index] = new ScrollMagic.Scene({
triggerElement: trigger,
triggerHook: 'onCenter',
duration: '50%'
})
.addIndicators({
name: trigger,
colorEnd: "#00FFFF"
})
.on('enter', function() {
let audio = $('audio')
console.log('Playing audio at index', index)
audio[index].play();
})
.on('leave', function() {
console.log('Leave' + trigger);
})
.addTo(controller);
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.6/ScrollMagic.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.6/plugins/debug.addIndicators.min.js"></script>
<div class="slide" id="slide-1">
<div class="trigger"></div>
<audio class="audio" src="https://sample-videos.com/audio/mp3/crowd-cheering.mp3" preload="auto"></audio>
</div>
<div class="slide" id="slide-2">
<div class="trigger"></div>
<audio class="audio" src="https://sample-videos.com/audio/mp3/crowd-cheering.mp3" preload="auto"></audio>
</div>
<div class="slide" id="slide-3">
<div class="trigger"></div>
<audio class="audio" src="https://sample-videos.com/audio/mp3/crowd-cheering.mp3" preload="auto"></audio>
</div>