钢琴模拟器

这是一个使用 HTML、CSS 和 JavaScript 创建的钢琴模拟器。这个模拟器使用 Web Audio API 生成接近真实钢琴的声音,并允许用户使用键盘弹奏。

在这里插入图片描述

这个钢琴模拟器,包括以下功能:

  1. 钢琴键盘的可视化界面
  2. 使用 Web Audio API 生成高质量的钢琴音色
  3. 键盘映射,允许使用电脑键盘弹奏
  4. 视觉反馈,当按下一个键时,对应的钢琴键会有按下的动画效果

使用说明

将上面的代码保存为一个HTML文件,然后在浏览器中打开。

使用键盘按键来弹奏钢琴:

白键对应键盘上的 A, S, D, F, G, H, J, K, L, ;, ', Z, X, C
黑键对应键盘上的 W, E, T, Y, U, O, P, Q, I, [
页面底部有音量控制滑块,可以调整钢琴音量。

延音踏板按钮(或按空格键)可以切换延音效果,使音符持续播放。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>钢琴模拟器</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #121212;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            font-family: 'Arial', sans-serif;
            color: #fff;
        }

        h1 {
            margin-bottom: 20px;
        }

        .piano {
            background-color: #000;
            padding: 40px 20px 20px;
            border-radius: 10px;
            box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
            position: relative;
        }

        .instructions {
            margin: 20px 0;
            text-align: center;
            font-size: 14px;
            color: #aaa;
        }

        .keys {
            display: flex;
            position: relative;
            width: 980px;
        }

        .white-key {
            width: 70px;
            height: 280px;
            background: linear-gradient(to bottom, #fff 0%, #f9f9f9 100%);
            border: 1px solid #ccc;
            border-radius: 0 0 5px 5px;
            color: #333;
            position: relative;
            margin: 0 1px;
            box-shadow: 0 5px 0 #ddd;
            transition: all 0.1s ease;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            padding-bottom: 10px;
            font-size: 14px;
            font-weight: bold;
        }

        .white-key.active {
            background: linear-gradient(to bottom, #ddd 0%, #eee 100%);
            transform: translateY(5px);
            box-shadow: none;
        }

        .black-key {
            position: absolute;
            width: 40px;
            height: 160px;
            background: linear-gradient(to bottom, #333 0%, #000 100%);
            border-radius: 0 0 3px 3px;
            box-shadow: 0 3px 0 rgba(0, 0, 0, 0.7), inset 0 -1px 0 rgba(255, 255, 255, 0.2);
            z-index: 2;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            padding-bottom: 10px;
            color: #fff;
            font-size: 12px;
            transition: all 0.1s ease;
        }

        .black-key.active {
            background: linear-gradient(to bottom, #000 0%, #222 100%);
            transform: translateY(3px);
            box-shadow: none;
        }

        .controls {
            display: flex;
            margin-top: 20px;
            gap: 20px;
            flex-wrap: wrap;
            justify-content: center;
        }

        .control-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .control {
            background: #333;
            border: none;
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .control:hover {
            background: #444;
        }

        .control:disabled {
            background: #222;
            color: #666;
            cursor: not-allowed;
        }

        .volume-control {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .volume-slider {
            width: 120px;
        }

        .piano-brand {
            position: absolute;
            top: 10px;
            width: 100%;
            text-align: center;
            font-family: 'Times New Roman', serif;
            font-style: italic;
            font-size: 24px;
            color: #666;
        }

        .song-selector {
            background: #333;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
        }

        .autoplay-controls {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }

        .file-input {
            position: absolute;
            font-size: 100px;
            opacity: 0;
            right: 0;
            top: 0;
            cursor: pointer;
        }

        .progress-bar {
            width: 100%;
            height: 5px;
            margin-top: 10px;
            background-color: #333;
            border-radius: 3px;
            overflow: hidden;
        }

        .progress {
            height: 100%;
            width: 0;
            background-color: #007bff;
            transition: width 0.1s linear;
        }

        .tempo-control {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .import-section {
            margin-top: 20px;
            background: #222;
            padding: 15px;
            border-radius: 8px;
            max-width: 980px;
        }

        .import-section h3 {
            margin-top: 0;
            margin-bottom: 15px;
        }

        .note-display {
            margin-top: 10px;
            background: #222;
            padding: 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 14px;
            color: #aaa;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>钢琴模拟器</h1>
    
    <div class="piano">
        <div class="piano-brand">Grand Piano</div>
        <div class="keys">
            <!-- 白键 -->
            <div class="white-key" data-note="C3" data-key="a">A</div>
            <div class="white-key" data-note="D3" data-key="s">S</div>
            <div class="white-key" data-note="E3" data-key="d">D</div>
            <div class="white-key" data-note="F3" data-key="f">F</div>
            <div class="white-key" data-note="G3" data-key="g">G</div>
            <div class="white-key" data-note="A3" data-key="h">H</div>
            <div class="white-key" data-note="B3" data-key="j">J</div>
            <div class="white-key" data-note="C4" data-key="k">K</div>
            <div class="white-key" data-note="D4" data-key="l">L</div>
            <div class="white-key" data-note="E4" data-key=";">;</div>
            <div class="white-key" data-note="F4" data-key="'">'</div>
            <div class="white-key" data-note="G4" data-key="z">Z</div>
            <div class="white-key" data-note="A4" data-key="x">X</div>
            <div class="white-key" data-note="B4" data-key="c">C</div>
            
            <!-- 黑键 -->
            <div class="black-key" data-note="C#3" data-key="w" style="left: 50px;">W</div>
            <div class="black-key" data-note="D#3" data-key="e" style="left: 120px;">E</div>
            <div class="black-key" data-note="F#3" data-key="t" style="left: 262px;">T</div>
            <div class="black-key" data-note="G#3" data-key="y" style="left: 332px;">Y</div>
            <div class="black-key" data-note="A#3" data-key="u" style="left: 402px;">U</div>
            <div class="black-key" data-note="C#4" data-key="o" style="left: 542px;">O</div>
            <div class="black-key" data-note="D#4" data-key="p" style="left: 612px;">P</div>
            <div class="black-key" data-note="F#4" data-key="q" style="left: 754px;">Q</div>
            <div class="black-key" data-note="G#4" data-key="i" style="left: 824px;">I</div>
            <div class="black-key" data-note="A#4" data-key="[" style="left: 894px;">[</div>
        </div>
        <div class="progress-bar">
            <div class="progress" id="song-progress"></div>
        </div>
    </div>
    
    <div class="note-display" id="current-note">
        当前播放: -
    </div>

    <div class="instructions">
        使用键盘上显示的按键来弹奏钢琴
    </div>
    
    <div class="controls">
        <div class="volume-control">
            <label for="volume">音量:</label>
            <input type="range" id="volume" class="volume-slider" min="0" max="1" step="0.01" value="0.5">
        </div>
        
        <div class="control-group">
            <button class="control" id="sustain-pedal">延音踏板 (空格键)</button>
        </div>
        
        <div class="autoplay-controls">
            <select id="song-selector" class="song-selector">
                <option value="">-- 选择乐曲 --</option>
                <option value="liangzhu">演示乐曲A</option>
                <option value="autumn_whisper">演示乐曲B</option>
            </select>
            <button class="control" id="play-button">自动弹奏</button>
            <button class="control" id="stop-button" disabled>停止播放</button>
        </div>
        
        <div class="tempo-control">
            <label for="tempo">速度:</label>
            <input type="range" id="tempo" class="volume-slider" min="0.5" max="2" step="0.1" value="1">
            <span id="tempo-value">1.0x</span>
        </div>
    </div>
    
    <div class="import-section">
        <h3>导入自定义乐曲</h3>
        <div class="file-input-wrapper">
            <button class="control">选择JSON文件</button>
            <input type="file" id="import-song" class="file-input" accept=".json">
        </div>
        <div id="import-status" style="margin-top: 10px; font-size: 14px; color: #aaa;"></div>
    </div>

    <script>
        // Web Audio API 上下文
        let audioContext;
        let masterGain;
        let sustainPedal = false;
        let activeNotes = {};
        
        // 自动播放变量
        let isPlaying = false;
        let playbackTimeout;
        let currentSongIndex = 0;
        let currentSong = null;
        let playbackSpeed = 1.0;
        
        // 音符频率映射
        const NOTES = {
            'C3': 130.81, 'C#3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'E3': 164.81, 'F3': 174.61,
            'F#3': 185.00, 'G3': 196.00, 'G#3': 207.65, 'A3': 220.00, 'A#3': 233.08, 'B3': 246.94,
            'C4': 261.63, 'C#4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'E4': 329.63, 'F4': 349.23,
            'F#4': 369.99, 'G4': 392.00, 'G#4': 415.30, 'A4': 440.00, 'A#4': 466.16, 'B4': 493.88,
            'C5': 523.25
        };
        
        // 键盘映射
        const keyToNote = {};
        const noteToKey = {};
        
        // 乐曲库
        const songsLibrary = {
            "liangzhu": {
                title: "演示乐曲B",
                notes: [
                    { note: "G3", duration: 500, startTime: 0 },
                    { note: "A3", duration: 500, startTime: 500 },
                    { note: "C4", duration: 500, startTime: 1000 },
                    { note: "D4", duration: 1000, startTime: 1500 },
                    { note: "E4", duration: 500, startTime: 2500 },
                    { note: "G4", duration: 500, startTime: 3000 },
                    { note: "E4", duration: 1000, startTime: 3500 },
                    { note: "D4", duration: 500, startTime: 4500 },
                    { note: "C4", duration: 500, startTime: 5000 },
                    { note: "A3", duration: 500, startTime: 5500 },
                    { note: "G3", duration: 1000, startTime: 6000 },
                    { note: "A3", duration: 500, startTime: 7000 },
                    { note: "C4", duration: 500, startTime: 7500 },
                    { note: "D4", duration: 500, startTime: 8000 },
                    { note: "E4", duration: 500, startTime: 8500 },
                    { note: "D4", duration: 500, startTime: 9000 },
                    { note: "C4", duration: 500, startTime: 9500 },
                    { note: "A3", duration: 500, startTime: 10000 },
                    { note: "G3", duration: 1500, startTime: 10500 },
                    { note: "C4", duration: 500, startTime: 12000 },
                    { note: "E4", duration: 500, startTime: 12500 },
                    { note: "G4", duration: 1000, startTime: 13000 },
                    { note: "A4", duration: 500, startTime: 14000 },
                    { note: "G4", duration: 500, startTime: 14500 },
                    { note: "E4", duration: 500, startTime: 15000 },
                    { note: "D4", duration: 500, startTime: 15500 },
                    { note: "C4", duration: 1500, startTime: 16000 }
                ]
            },
            "autumn_whisper": {
                title: "演示乐曲A",
                notes: [
                    { note: "E4", duration: 500, startTime: 0 },
                    { note: "G4", duration: 500, startTime: 500 },
                    { note: "A4", duration: 1000, startTime: 1000 },
                    { note: "G4", duration: 500, startTime: 2000 },
                    { note: "E4", duration: 500, startTime: 2500 },
                    { note: "D4", duration: 1000, startTime: 3000 },
                    { note: "E4", duration: 500, startTime: 4000 },
                    { note: "G4", duration: 500, startTime: 4500 },
                    { note: "A4", duration: 500, startTime: 5000 },
                    { note: "B4", duration: 500, startTime: 5500 },
                    { note: "A4", duration: 500, startTime: 6000 },
                    { note: "G4", duration: 500, startTime: 6500 },
                    { note: "E4", duration: 1000, startTime: 7000 },
                    { note: "D4", duration: 500, startTime: 8000 },
                    { note: "E4", duration: 500, startTime: 8500 },
                    { note: "G4", duration: 500, startTime: 9000 },
                    { note: "E4", duration: 500, startTime: 9500 },
                    { note: "D4", duration: 500, startTime: 10000 },
                    { note: "C4", duration: 1500, startTime: 10500 },
                    { note: "D4", duration: 500, startTime: 12000 },
                    { note: "E4", duration: 500, startTime: 12500 },
                    { note: "G4", duration: 500, startTime: 13000 },
                    { note: "A4", duration: 1000, startTime: 13500 },
                    { note: "G4", duration: 500, startTime: 14500 },
                    { note: "E4", duration: 500, startTime: 15000 },
                    { note: "D4", duration: 1500, startTime: 15500 }
                ]
            }
        };
                
        // 初始化
        function init() {
            try {
                // 创建 Audio Context
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
                masterGain = audioContext.createGain();
                masterGain.gain.value = 0.5;
                masterGain.connect(audioContext.destination);
                
                // 设置键盘映射
                document.querySelectorAll('.white-key, .black-key').forEach(key => {
                    const note = key.dataset.note;
                    const keyChar = key.dataset.key;
                    keyToNote[keyChar] = note;
                    noteToKey[note] = keyChar;
                });
                
                // 设置事件监听器
                document.addEventListener('keydown', handleKeyDown);
                document.addEventListener('keyup', handleKeyUp);
                
                // 鼠标/触摸事件
                document.querySelectorAll('.white-key, .black-key').forEach(key => {
                    key.addEventListener('mousedown', () => {
                        playNote(key.dataset.note);
                        key.classList.add('active');
                    });
                    
                    key.addEventListener('mouseup', () => {
                        if (!sustainPedal) {
                            stopNote(key.dataset.note);
                        }
                        key.classList.remove('active');
                    });
                    
                    key.addEventListener('mouseleave', () => {
                        if (!activeNotes[key.dataset.note]) {
                            key.classList.remove('active');
                        }
                    });
                });
                
                // 音量控制
                document.getElementById('volume').addEventListener('input', (e) => {
                    masterGain.gain.value = parseFloat(e.target.value);
                });
                
                // 延音踏板
                document.getElementById('sustain-pedal').addEventListener('click', toggleSustainPedal);
                
                // 乐曲选择
                document.getElementById('song-selector').addEventListener('change', function() {
                    const songId = this.value;
                    if (songId) {
                        currentSong = songsLibrary[songId];
                        currentSongIndex = 0;
                    } else {
                        currentSong = null;
                    }
                });
                
                // 播放按钮
                document.getElementById('play-button').addEventListener('click', function() {
                    if (!currentSong) {
                        alert('请先选择一首乐曲!');
                        return;
                    }
                    
                    if (isPlaying) {
                        stopPlayback();
                    }
                    
                    startPlayback();
                });
                
                // 停止按钮
                document.getElementById('stop-button').addEventListener('click', function() {
                    stopPlayback();
                });
                
                // 速度控制
                document.getElementById('tempo').addEventListener('input', function(e) {
                    playbackSpeed = parseFloat(e.target.value);
                    document.getElementById('tempo-value').textContent = playbackSpeed.toFixed(1) + 'x';
                });
                
                // 文件导入
                document.getElementById('import-song').addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (!file) return;
                    
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        try {
                            const songData = JSON.parse(e.target.result);
                            
                            // 验证JSON格式
                            if (!songData.title || !Array.isArray(songData.notes)) {
                                throw new Error('无效的JSON格式。需要包含 title 和 notes 数组');
                            }
                            
                            // 添加到乐曲库
                            const songId = 'custom_' + Date.now();
                            songsLibrary[songId] = songData;
                            
                            // 更新下拉菜单
                            const selector = document.getElementById('song-selector');
                            const option = document.createElement('option');
                            option.value = songId;
                            option.textContent = songData.title;
                            selector.appendChild(option);
                            
                            // 设置为当前乐曲
                            selector.value = songId;
                            currentSong = songData;
                            
                            document.getElementById('import-status').textContent = `成功导入: ${songData.title}`;
                        } catch (error) {
                            document.getElementById('import-status').textContent = '错误: ' + error.message;
                        }
                    };
                    
                    reader.readAsText(file);
                });
            } catch (e) {
                console.error('Web Audio API 不支持', e);
                alert('您的浏览器不支持 Web Audio API,请使用现代浏览器如 Chrome, Firefox, Safari 或 Edge。');
            }
        }
        
        // 播放音符
        function playNote(note) {
            if (!audioContext) return;
            
            if (audioContext.state === 'suspended') {
                audioContext.resume();
            }
            
            // 创建振荡器
            const oscillator = audioContext.createOscillator();
            const oscillatorGain = audioContext.createGain();
            
            // 设置音色(接近钢琴的波形)
            oscillator.type = 'triangle';
            
            // 设置频率(基于音符)
            oscillator.frequency.value = NOTES[note];
            
            // 创建包络
            oscillatorGain.gain.value = 0;
            
            // 连接节点
            oscillator.connect(oscillatorGain);
            oscillatorGain.connect(masterGain);
            
            // 开始播放
            oscillator.start();
            
            // 应用ADSR包络以接近钢琴音色
            const now = audioContext.currentTime;
            oscillatorGain.gain.setValueAtTime(0, now);
            oscillatorGain.gain.linearRampToValueAtTime(0.8, now + 0.01); // 快速攻击
            oscillatorGain.gain.linearRampToValueAtTime(0.6, now + 0.1); // 快速衰减
            oscillatorGain.gain.exponentialRampToValueAtTime(0.4, now + 0.5); // 延音
            
            // 存储活跃音符
            activeNotes[note] = {
                oscillator: oscillator,
                gain: oscillatorGain,
                startTime: now
            };
            
            // 显示按键被按下
            const keyElement = document.querySelector(`[data-note="${note}"]`);
            if (keyElement) {
                keyElement.classList.add('active');
            }
            
            // 更新当前播放的音符显示
            document.getElementById('current-note').textContent = `当前播放: ${note}`;
        }
        
        // 停止音符
        function stopNote(note) {
            if (!activeNotes[note]) return;
            
            const now = audioContext.currentTime;
            const { oscillator, gain } = activeNotes[note];
            
            // 释音(钢琴音色的释音特性)
            gain.gain.cancelScheduledValues(now);
            gain.gain.setValueAtTime(gain.gain.value, now);
            gain.gain.exponentialRampToValueAtTime(0.001, now + 1.5);
            
            // 在释音结束后停止振荡器
            setTimeout(() => {
                oscillator.stop();
                oscillator.disconnect();
                gain.disconnect();
            }, 1500);
            
            delete activeNotes[note];
            
            // 移除按键按下状态
            const keyElement = document.querySelector(`[data-note="${note}"]`);
            if (keyElement) {
                keyElement.classList.remove('active');
            }
        }
        
        // 处理键盘按下事件
        function handleKeyDown(e) {
            if (e.repeat) return; // 防止键盘重复事件
            
            const key = e.key.toLowerCase();
            
            // 空格键控制延音踏板
            if (key === ' ') {
                toggleSustainPedal();
                return;
            }
            
            if (keyToNote[key]) {
                const note = keyToNote[key];
                if (!activeNotes[note]) {
                    playNote(note);
                }
            }
        }
        
        // 处理键盘释放事件
        function handleKeyUp(e) {
            const key = e.key.toLowerCase();
            
            if (key === ' ') return; // 延音踏板由点击控制
            
            if (keyToNote[key]) {
                const note = keyToNote[key];
                if (!sustainPedal && activeNotes[note]) {
                    stopNote(note);
                }
            }
        }
        
        // 切换延音踏板
        function toggleSustainPedal() {
            sustainPedal = !sustainPedal;
            const pedalButton = document.getElementById('sustain-pedal');
            
            if (sustainPedal) {
                pedalButton.style.background = '#007bff';
            } else {
                pedalButton.style.background = '#333';
                
                // 停止所有音符
                Object.keys(activeNotes).forEach(note => {
                    stopNote(note);
                });
            }
        }
        
        // 开始自动播放
        function startPlayback() {
            if (!currentSong || isPlaying) return;
            
            isPlaying = true;
            currentSongIndex = 0;
            
            document.getElementById('play-button').disabled = true;
            document.getElementById('stop-button').disabled = false;
            document.getElementById('song-selector').disabled = true;
            
            playNextNote();
            updateProgressBar();
        }
        
        // 停止自动播放
        function stopPlayback() {
            isPlaying = false;
            
            if (playbackTimeout) {
                clearTimeout(playbackTimeout);
                playbackTimeout = null;
            }
            
            // 停止所有音符
            Object.keys(activeNotes).forEach(note => {
                stopNote(note);
            });
            
            document.getElementById('play-button').disabled = false;
            document.getElementById('stop-button').disabled = true;
            document.getElementById('song-selector').disabled = false;
            document.getElementById('current-note').textContent = '当前播放: -';
            
            // 重置进度条
            document.getElementById('song-progress').style.width = '0%';
        }
        
        // 播放下一个音符
        function playNextNote() {
            if (!isPlaying || !currentSong || currentSongIndex >= currentSong.notes.length) {
                stopPlayback();
                return;
            }
            
            const noteData = currentSong.notes[currentSongIndex];
            const adjustedDuration = noteData.duration / playbackSpeed;
            
            // 播放当前音符
            playNote(noteData.note);
            
            // 安排停止当前音符
            setTimeout(() => {
                if (!sustainPedal) {
                    stopNote(noteData.note);
                }
            }, adjustedDuration * 0.9); // 稍微提前释放音符以防重叠
            
            // 安排下一个音符
            currentSongIndex++;
            
            if (currentSongIndex < currentSong.notes.length) {
                const nextNoteData = currentSong.notes[currentSongIndex];
                const currentStartTime = noteData.startTime;
                const nextStartTime = nextNoteData.startTime;
                const timeToNextNote = (nextStartTime - currentStartTime) / playbackSpeed;
                
                playbackTimeout = setTimeout(playNextNote, timeToNextNote);
            } else {
                // 完成播放
                playbackTimeout = setTimeout(stopPlayback, adjustedDuration);
            }
        }
        
        // 更新进度条
        function updateProgressBar() {
            if (!isPlaying || !currentSong) return;
            
            const totalDuration = currentSong.notes[currentSong.notes.length - 1].startTime + 
                                 currentSong.notes[currentSong.notes.length - 1].duration;
            
            const currentTime = currentSongIndex > 0 
                ? currentSong.notes[currentSongIndex - 1].startTime 
                : 0;
                
            const progress = (currentTime / totalDuration) * 100;
            document.getElementById('song-progress').style.width = `${progress}%`;
            
            setTimeout(updateProgressBar, 100);
        }
        
        // 初始化应用
        window.addEventListener('load', init);
    </script>
</body>
</html>

优化方向

如果你想要更逼真的钢琴声音,可以考虑以下改进:

  1. 使用实际的钢琴采样库(如 Salamander Grand Piano)替代合成的钢琴音色。
  2. 实现力度感应,根据按键的力度改变音量和音色。
  3. 添加更复杂的钢琴物理模型,包括弦振动、共鸣和击弦机制。
  4. 添加混响效果以模拟钢琴在不同空间中的声音。

这个模拟器提供了基本的钢琴体验,使用了Web Audio API生成接近钢琴的音色,并有视觉反馈。随着浏览器功能的增强,可以进一步改进以获得更真实的体验。

下面是完整的代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>钢琴模拟器</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #121212;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            font-family: 'Arial', sans-serif;
            color: #fff;
        }

        h1 {
            margin-bottom: 20px;
        }

        .piano {
            background-color: #000;
            padding: 40px 20px 20px;
            border-radius: 10px;
            box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
            position: relative;
        }

        .instructions {
            margin: 20px 0;
            text-align: center;
            font-size: 14px;
            color: #aaa;
        }

        .keys {
            display: flex;
            position: relative;
            width: 980px;
        }

        .white-key {
            width: 70px;
            height: 280px;
            background: linear-gradient(to bottom, #fff 0%, #f9f9f9 100%);
            border: 1px solid #ccc;
            border-radius: 0 0 5px 5px;
            color: #333;
            position: relative;
            margin: 0 1px;
            box-shadow: 0 5px 0 #ddd;
            transition: all 0.1s ease;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            padding-bottom: 10px;
            font-size: 14px;
            font-weight: bold;
        }

        .white-key.active {
            background: linear-gradient(to bottom, #ddd 0%, #eee 100%);
            transform: translateY(5px);
            box-shadow: none;
        }

        .black-key {
            position: absolute;
            width: 40px;
            height: 160px;
            background: linear-gradient(to bottom, #333 0%, #000 100%);
            border-radius: 0 0 3px 3px;
            box-shadow: 0 3px 0 rgba(0, 0, 0, 0.7), inset 0 -1px 0 rgba(255, 255, 255, 0.2);
            z-index: 2;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            padding-bottom: 10px;
            color: #fff;
            font-size: 12px;
            transition: all 0.1s ease;
        }

        .black-key.active {
            background: linear-gradient(to bottom, #000 0%, #222 100%);
            transform: translateY(3px);
            box-shadow: none;
        }

        .controls {
            display: flex;
            margin-top: 20px;
            gap: 20px;
        }

        .control {
            background: #333;
            border: none;
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .control:hover {
            background: #444;
        }

        .volume-control {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .volume-slider {
            width: 120px;
        }

        .piano-brand {
            position: absolute;
            top: 10px;
            width: 100%;
            text-align: center;
            font-family: 'Times New Roman', serif;
            font-style: italic;
            font-size: 24px;
            color: #666;
        }
    </style>
</head>
<body>
    <h1>钢琴模拟器</h1>
    
    <div class="piano">
        <div class="piano-brand">Grand Piano</div>
        <div class="keys">
            <!-- 白键 -->
            <div class="white-key" data-note="C3" data-key="a">A</div>
            <div class="white-key" data-note="D3" data-key="s">S</div>
            <div class="white-key" data-note="E3" data-key="d">D</div>
            <div class="white-key" data-note="F3" data-key="f">F</div>
            <div class="white-key" data-note="G3" data-key="g">G</div>
            <div class="white-key" data-note="A3" data-key="h">H</div>
            <div class="white-key" data-note="B3" data-key="j">J</div>
            <div class="white-key" data-note="C4" data-key="k">K</div>
            <div class="white-key" data-note="D4" data-key="l">L</div>
            <div class="white-key" data-note="E4" data-key=";">;</div>
            <div class="white-key" data-note="F4" data-key="'">'</div>
            <div class="white-key" data-note="G4" data-key="z">Z</div>
            <div class="white-key" data-note="A4" data-key="x">X</div>
            <div class="white-key" data-note="B4" data-key="c">C</div>
            
            <!-- 黑键 -->
            <div class="black-key" data-note="C#3" data-key="w" style="left: 50px;">W</div>
            <div class="black-key" data-note="D#3" data-key="e" style="left: 120px;">E</div>
            <div class="black-key" data-note="F#3" data-key="t" style="left: 262px;">T</div>
            <div class="black-key" data-note="G#3" data-key="y" style="left: 332px;">Y</div>
            <div class="black-key" data-note="A#3" data-key="u" style="left: 402px;">U</div>
            <div class="black-key" data-note="C#4" data-key="o" style="left: 542px;">O</div>
            <div class="black-key" data-note="D#4" data-key="p" style="left: 612px;">P</div>
            <div class="black-key" data-note="F#4" data-key="q" style="left: 754px;">Q</div>
            <div class="black-key" data-note="G#4" data-key="i" style="left: 824px;">I</div>
            <div class="black-key" data-note="A#4" data-key="[" style="left: 894px;">[</div>
        </div>
    </div>
    
    <div class="instructions">
        使用键盘上显示的按键来弹奏钢琴
    </div>
    
    <div class="controls">
        <div class="volume-control">
            <label for="volume">音量:</label>
            <input type="range" id="volume" class="volume-slider" min="0" max="1" step="0.01" value="0.5">
        </div>
        <button class="control" id="sustain-pedal">延音踏板 (空格键)</button>
    </div>

    <script>
        // Web Audio API 上下文
        let audioContext;
        let masterGain;
        let sustainPedal = false;
        let activeNotes = {};
        
        // 音符频率映射
        const NOTES = {
            'C3': 130.81, 'C#3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'E3': 164.81, 'F3': 174.61,
            'F#3': 185.00, 'G3': 196.00, 'G#3': 207.65, 'A3': 220.00, 'A#3': 233.08, 'B3': 246.94,
            'C4': 261.63, 'C#4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'E4': 329.63, 'F4': 349.23,
            'F#4': 369.99, 'G4': 392.00, 'G#4': 415.30, 'A4': 440.00, 'A#4': 466.16, 'B4': 493.88
        };
        
        // 键盘映射
        const keyToNote = {};
        const noteToKey = {};
        
        // 加载音频
        let pianoSamples = {};
        let loadingPromises = [];
                
        // 初始化
        function init() {
            try {
                // 创建 Audio Context
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
                masterGain = audioContext.createGain();
                masterGain.gain.value = 0.5;
                masterGain.connect(audioContext.destination);
                
                // 设置键盘映射
                document.querySelectorAll('.white-key, .black-key').forEach(key => {
                    const note = key.dataset.note;
                    const keyChar = key.dataset.key;
                    keyToNote[keyChar] = note;
                    noteToKey[note] = keyChar;
                });
                
                // 设置事件监听器
                document.addEventListener('keydown', handleKeyDown);
                document.addEventListener('keyup', handleKeyUp);
                
                // 鼠标/触摸事件
                document.querySelectorAll('.white-key, .black-key').forEach(key => {
                    key.addEventListener('mousedown', () => {
                        playNote(key.dataset.note);
                        key.classList.add('active');
                    });
                    
                    key.addEventListener('mouseup', () => {
                        if (!sustainPedal) {
                            stopNote(key.dataset.note);
                        }
                        key.classList.remove('active');
                    });
                    
                    key.addEventListener('mouseleave', () => {
                        if (!activeNotes[key.dataset.note]) {
                            key.classList.remove('active');
                        }
                    });
                });
                
                // 音量控制
                document.getElementById('volume').addEventListener('input', (e) => {
                    masterGain.gain.value = parseFloat(e.target.value);
                });
                
                // 延音踏板
                document.getElementById('sustain-pedal').addEventListener('click', toggleSustainPedal);
                
                // 加载钢琴音色
                loadPianoSamples();
                
            } catch (e) {
                console.error('Web Audio API 不支持', e);
                alert('您的浏览器不支持 Web Audio API,请使用现代浏览器如 Chrome, Firefox, Safari 或 Edge。');
            }
        }
        
        // 加载钢琴音色
        async function loadPianoSamples() {
            // 简化示例,实际项目中可以加载真实的钢琴采样
            // 这里使用合成的钢琴音色
        }
        
        // 播放音符
        function playNote(note) {
            if (!audioContext) return;
            
            if (audioContext.state === 'suspended') {
                audioContext.resume();
            }
            
            // 创建振荡器
            const oscillator = audioContext.createOscillator();
            const oscillatorGain = audioContext.createGain();
            
            // 设置音色(接近钢琴的波形)
            oscillator.type = 'triangle';
            
            // 设置频率(基于音符)
            oscillator.frequency.value = NOTES[note];
            
            // 创建包络
            oscillatorGain.gain.value = 0;
            
            // 连接节点
            oscillator.connect(oscillatorGain);
            oscillatorGain.connect(masterGain);
            
            // 开始播放
            oscillator.start();
            
            // 应用ADSR包络以接近钢琴音色
            const now = audioContext.currentTime;
            oscillatorGain.gain.setValueAtTime(0, now);
            oscillatorGain.gain.linearRampToValueAtTime(0.8, now + 0.01); // 快速攻击
            oscillatorGain.gain.linearRampToValueAtTime(0.6, now + 0.1); // 快速衰减
            oscillatorGain.gain.exponentialRampToValueAtTime(0.4, now + 0.5); // 延音
            
            // 存储活跃音符
            activeNotes[note] = {
                oscillator: oscillator,
                gain: oscillatorGain,
                startTime: now
            };
            
            // 显示按键被按下
            const keyElement = document.querySelector(`[data-note="${note}"]`);
            if (keyElement) {
                keyElement.classList.add('active');
            }
        }
        
        // 停止音符
        function stopNote(note) {
            if (!activeNotes[note]) return;
            
            const now = audioContext.currentTime;
            const { oscillator, gain } = activeNotes[note];
            
            // 释音(钢琴音色的释音特性)
            gain.gain.cancelScheduledValues(now);
            gain.gain.setValueAtTime(gain.gain.value, now);
            gain.gain.exponentialRampToValueAtTime(0.001, now + 1.5);
            
            // 在释音结束后停止振荡器
            setTimeout(() => {
                oscillator.stop();
                oscillator.disconnect();
                gain.disconnect();
            }, 1500);
            
            delete activeNotes[note];
            
            // 移除按键按下状态
            const keyElement = document.querySelector(`[data-note="${note}"]`);
            if (keyElement) {
                keyElement.classList.remove('active');
            }
        }
        
        // 处理键盘按下事件
        function handleKeyDown(e) {
            if (e.repeat) return; // 防止键盘重复事件
            
            const key = e.key.toLowerCase();
            
            // 空格键控制延音踏板
            if (key === ' ') {
                toggleSustainPedal();
                return;
            }
            
            if (keyToNote[key]) {
                const note = keyToNote[key];
                if (!activeNotes[note]) {
                    playNote(note);
                }
            }
        }
        
        // 处理键盘释放事件
        function handleKeyUp(e) {
            const key = e.key.toLowerCase();
            
            if (key === ' ') return; // 延音踏板由点击控制
            
            if (keyToNote[key]) {
                const note = keyToNote[key];
                if (!sustainPedal && activeNotes[note]) {
                    stopNote(note);
                }
            }
        }
        
        // 切换延音踏板
        function toggleSustainPedal() {
            sustainPedal = !sustainPedal;
            const pedalButton = document.getElementById('sustain-pedal');
            
            if (sustainPedal) {
                pedalButton.style.background = '#007bff';
            } else {
                pedalButton.style.background = '#333';
                
                // 停止所有音符
                Object.keys(activeNotes).forEach(note => {
                    stopNote(note);
                });
            }
        }
        
        // 初始化应用
        window.addEventListener('load', init);
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值