2024/12/18 piano

2024/12/18 piano

<!DOCTYPE html>
<html lang=”ja”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width,initial-scale=1.0″>
<title>簡易ピアノ</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
}
.key {
display: inline-block;
width: 50px;
height: 150px;
margin: 5px;
background-color: white;
border: 1px solid black;
text-align: center;
line-height: 150px;
cursor: pointer;
user-select: none;
}
.key:active {
background-color: lightgray;
}
.black {
background-color: black;
color: white;
height: 100px;
margin-left: -25px;
margin-right: -25px;
z-index: 1;
position: relative;
line-height: 100px;
}
.black:active {
background-color: gray;
}
</style>
</head>
<body>
<h1>簡易ピアノ</h1>
<div id=”piano”>
<div class=”key” data-note=”261.63″>C</div>
<div class=”key black” data-note=”277.18″>C#</div>
<div class=”key” data-note=”293.66″>D</div>
<div class=”key black” data-note=”311.13″>D#</div>
<div class=”key” data-note=”329.63″>E</div>
<div class=”key” data-note=”349.23″>F</div>
<div class=”key black” data-note=”369.99″>F#</div>
<div class=”key” data-note=”392.00″>G</div>
<div class=”key black” data-note=”415.30″>G#</div>
<div class=”key” data-note=”440.00″>A</div>
<div class=”key black” data-note=”466.16″>A#</div>
<div class=”key” data-note=”493.88″>B</div>
</div>
<script>
const audioContext = new (window.AudioContext || window.webkitAudioContext)();

function playSound(frequency) {
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();

oscillator.type = ‘sine’; // 波形の種類 (sine, square, sawtooth, triangle)
oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);

oscillator.start();
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 0.5);
oscillator.stop(audioContext.currentTime + 0.5);
}

document.getElementById(‘piano’).addEventListener(‘click’, (e) => {
if (e.target.classList.contains(‘key’)) {
const frequency = parseFloat(e.target.dataset.note);
if (!isNaN(frequency)) {
playSound(frequency);
}
}
});
</script>
</body>
</html>

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です