I want to change audio source onClick button. I am trying this but I can't take a result. enter image description here
data() {
return {
audioSrc: ''
}
},
methods: {
setActiveAudio(item) {
this.$refs.audioElm.src = item;
this.$refs.audioElm.currentTime = 0;
this.$refs.audioElm.crossOrigin = 'anonymus';
this.$refs.audioElm.play();
},
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<span class="voice-btn" @click="setActiveAudio('../assets/voice.mp3')"> Click Sound</span>
<audio ref="audioElm" :src="audioSrc"></audio>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You have to use a timer to make sure the DOM has been updated before you interact with the element like
data() {
return {
audioSrc: ''
}
},
methods: {
setActiveAudio(item) {
this.audioSrc = item;
var element = this.$refs.audioElm;
setTimeout(function()
{
element.currentTime = 0;
element.crossOrigin = 'anonymus';
element.play();
}, 0);
},
}
Working example on https://jsfiddle.net/AndersBillLinden/6x8hzrga/