[英]Play an MP3 on click in NextJS
我是 JS 框架的新手,我可能會弄錯 function 語法。 這就是我所擁有的,我的想法是,單擊按鈕后,它將播放一個快速音頻文件,該文件在音頻標簽中的按鈕下方指定。 知道如何讓這個工作嗎?
import Head from 'next/head'
export default function Home() {
function play() {
var audio = document.getElementById('a1');
audio.play();
}
return (
<div className='home'>
<Head>
<title>Create Next App</title>
<link rel='icon' href='/favicon.ico' />
</Head>
<div className='container'>
<div className='col'>
<button onClick={play()}>Click</button>
<audio id='a1' src='/static/src.mp3'></audio>
</div>
您不應該用括號調用 function 而是傳遞引用。 嘗試這個:
<button onClick={play}>Click</button>
<button onClick={play}>Click</button>
<audio id='a1'>
<source src='/static/src.mp3' type='audio/mpeg' />
Your browser does not support the audio element.
</audio>
也許 src 有問題,您可以在您的 src https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3上進行測試
或者您可以使用useRef
來定位元素而不是document.getElementById
您可能想嘗試使用useRef
保存對<audio />
標簽的引用:
import { useRef } from 'react';
export default function Home() {
const audioRef = useRef();
const play = () => {
if (audioRef.current) {
audioRef.current.play()
} else {
// Throw error
}
}
return (
<div>
<button onClick={play}>Play</button>
<audio ref={audioRef} src='/static/src.mp3' />
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.