I'm making a note sequencer web application and I am currently trying to implement the function of playing a note on pressing a button corresponding to the note. I am currently using a test sound to understand how playing audio works as this is my first time dealing with audio in HTML.
I am also using webpack, and my problem at first was getting webpack to recognize the mp3 file, but I quickly solved that by using file-loader
.
Now my problem lies in the fact that the test audio I am using does not play on the click of a button, but does play perfectly fine onload of the site. There are no errors given to me by the console.
Here is script.js
: (note: this may be poorly written for the meantime of me understanding this issue)
import "./style.css";
import myAudioResource from './click-234708.mp3';
const CONTROL_BAR = document.createElement("div");
CONTROL_BAR.id = "control-bar";
const MAIN_BAR = document.createElement("div");
MAIN_BAR.id = "main-bar";
const testbutton = document.createElement("button");
const testaudio = new Audio();
testaudio.src = myAudioResource;
testbutton.addEventListener('click', testaudio.play())
MAIN_BAR.appendChild(testbutton);
const SCALE_BAR = document.createElement("div");
SCALE_BAR.id = "scale-bar";
const MAIN = document.createElement("div");
MAIN.id = "main";
MAIN.appendChild(CONTROL_BAR);
MAIN.appendChild(MAIN_BAR);
MAIN.appendChild(SCALE_BAR);
document.body.appendChild(MAIN);
I want to make testaudio
play on clicking testbutton
, and NOT onload of the site.
Here is webpack.config.js
:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'development',
entry: "./src/script.js",
devtool: 'inline-source-map',
output: {
filename: "main.js",
path: path.resolve(__dirname, 'dist'),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
title: 'Leitmotif',
filename: 'index.html',
template: './src/template.html',
})
],
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.mp3/,
loader: 'file-loader',
},
],
},
};
I attempted some of the solutions in this forum but to no avail.
I do believe this could be a problem with the way I've written my program, considering I have to also ensure everything works well with webpack. I have tried different syntaxes and creating separate functions to play the audio, but all of it just ended up playing the audio on load again.
Can anyone help out here?
try to substitute testbutton.addEventListener('click', testaudio.play())
with testbutton.addEventListener('click', () => {testaudio.play()})