Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

javascript - Trying to play an audiofile onClick in React.js

I'm building a Todo list with some extra features built in. One of the features I'm trying to implement is when a todo item is marked 'completed' the item is crossed off and an audiofile of kids saying "yay" in unison will play. I have the audiofile in a folder marked "audioclips." I have my Todo.js file that I'm working in, in a folder named components. I don't believe the audio clip needs to be imported with the message that I'm using. I believe that I'm navigating the files right when declaring the src. I've tried console-logging the audio id and I get

Promise {<pending>}

Any ideas to correct my mistake? Or perhaps a better way to play the audio file onClick? Thanks!

const completeHandler = () => {
    setTodos(todos.map((item) => { 
        
        if(item.id === todo.id) { 
            console.log("COMPLETED")
            console.log(document.getElementById("audio").play())
            return { 
                ...item, completed: !item.completed  
            };
        }

        return item; 
    }))
}

return(
    <div className="todo">
        <li className={`todo-item ${todo.completed ? "completed" : ""}`}>
            {text}
        </li>  
        <button onClick={completeHandler} className="complete-btn">
            <i className="fas fa-check"></i>
        </button>
        <audio id="audio">
            <source src="../audioclips/kidscheering.mp3"></source>
        </audio>
    </div>
);

}

question from:https://stackoverflow.com/questions/65851825/trying-to-play-an-audiofile-onclick-in-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...