I think that an audio object is throwing a ReferenceError when building on Gatsby and I don't really know why. I've read it may be because of Node.JS, so I guess the way I'm creating the audio object is not the right one. The develop version works completely fine tho. This is the component where I created the audio object:
const Button = value => {
const [play, setPlay] = useState(false);
//Switch state
const switchit = () => {setPlay(!play)}
//Getting track info
const track = value.value
const trackName = track && track.name ? track.name : null;
const trackPath = track && track.publicURL ? track.publicURL : null;
//Making track playable
const playAudio = new Audio(trackPath)
const playSound = () => {
if (play === false) {
playAudio.play();
switchit()
setTimeout(() => {
setPlay(false)
}, playAudio.duration * 1000);
} else {}
}
return (
<>
<ButtonStyle onClick={playSound}>{trackName}</ButtonStyle>
</>
)
}
export default Button
And this is the error thrown when I try to build the project:
ERROR
Page data from page-data.json for the failed page "/": {
"componentChunkName": "component---src-pages-index-js",
"path": "/",
"result": {
"pageContext": {}
},
"staticQueryHashes": [
"3649515864",
"3652344105",
"63159454"
]
}
failed Building static HTML for pages - 3.380s
ERROR #95313
Building static HTML failed for path "/"
See our docs page for more info on this error: https://gatsby.dev/debug-html
WebpackError: ReferenceError: Audio is not defined
- index.js:15
webpack:/facusounds/src/components/Button/index.js:15:21
- index.js:22
[facusounds]/[decode-uri-component]/index.js:22:1
- index.js:25
[facusounds]/[decode-uri-component]/index.js:25:1
- index.js:31
[facusounds]/[decode-uri-component]/index.js:31:1
- index.js:30
[facusounds]/[decode-uri-component]/index.js:30:4
- index.js:41
[facusounds]/[decode-uri-component]/index.js:41:1
- static-entry.js:294
webpack:/facusounds/.cache/static-entry.js:294:22
- dev-404-page.js:15
facusounds/.cache/dev-404-page.js:15:11
CodePudding user response:
Gatsby is trying to access the Audio
object, which is only available client side. You'll need to add some conditional logic that checks for the availability of the global window
object.
const [playAudio] = useState(window !== 'undefined' ? new Audio(trackPath) : null)
If you need to update the Audio
object when trackPath
changes, you can use useEffect
which only runs client side (so no need for window check):
const [playAudio, setAudio] = useState(null)
useEffect(() => {
setAudio(new Audio(trackPath))
}, [trackPath])