简体   繁体   中英

Play an MP3 on click in NextJS

I'm new with JS frameworks, I could be getting the function syntax wrong. This is what I have, the idea is that upon clicking the button it will play a quick audio file which is designated below the button in the Audio tags. Any idea how I can get this working?

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>

You shouldn't call the function with parenthesis but pass the reference. Try this:

   <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>

maybe something's wrong with src, you can test this on your src https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3

or maybe you can use useRef to target the element instead of document.getElementById

You might want to try holding a ref to the <audio /> tag with useRef :

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>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM