import React, { useRef } from 'react'
import Flex from '../UI/FlexBox/Flex'
import styles from './Piano.module.scss'
import audioFilePath from '../../assets/notes/PIANOS.mp3'
import { useState } from 'react';
import { useEffect } from 'react';
import { useMemo } from 'react';
import { IoMdMusicalNote } from "react-icons/io";
import { FaLongArrowAltUp, FaLongArrowAltDown } from "react-icons/fa";
function Piano() {
const [pressed,setPressed] = useState([])
const [exam,setExam] = useState({
stage:'prepare', // prepare listen play complite!
count:0,
notes:[],
guessed:[],
statistics:{},
});
const examRef = useRef(exam); // Для некоторых функций, где кешируются данные
const examLib = [
[
0,
4,
7
],
[
0,
5,
7
],
[
7,
5,
4
],
[
0,
2,
4
],
[
4,
5,
7
],
[
7,
5,
4
],
[
0,
7,
4
],
[
7,
0,
4
]
]
const setEmaxStage = (val) => setExam(prev=>({...prev,stage:val})); // prepare listen play
const setEmaxNotes = (val) => setExam(prev=>({...prev,notes:val}));
const addEmaxGuessed = (val) => setExam(prev=>({...prev, guessed: [ ...prev.guessed , val] }));
const clearEmaxGuessed = (val) => setExam(prev=>({...prev, guessed: [] }));
const increaseEmaxCount = () => setExam(prev=>({...prev, count: prev.count+1 }));
// EXAM ===========================================================
const testNote = (noteIndex) => {
if(exam.notes.length){
const guessed = exam.guessed.length
if(guessed===exam.notes.length) return false;
addEmaxGuessed( exam.notes[guessed] === noteIndex )
if(guessed===exam.notes.length-1){
// setEmaxStage(isComplite?'complite!':'wrong')
// if(isComplite) increaseEmaxCount()
setTimeout(()=>{
const isComplite = isTestComplite()
if(isComplite) startTest()
else repeatTest()
},1500)
}
}
}
const repeatTest = () => {
playEmaxNotes(exam.notes)
clearEmaxGuessed()
}
const getRandomNoteNumbers = (count, scale) => {
const result = []
for(let i = 0; i<count; i++){
const randomNumberOfScale = Math.floor(Math.random()*scale.length)
result.push( scale[randomNumberOfScale].index )
}
return result
}
const playEmaxNotes = (notes) => {
setEmaxStage('listen')
let count = 0;
const playEmaxNote = () => {
playNote(notes[count]);
count++
}
playEmaxNote();
const interval = setInterval(()=>{
playEmaxNote()
if(count === notes.length){
setEmaxStage('play');
clearInterval(interval)
}
},500);
}
const startTest = () => {
clearEmaxGuessed();
const exam = examRef.current;
// Только белые ноты в октаве / пентатоника
const scale = keys.filter( key => !key.black )
const notes = examLib[Math.floor(Math.random()*examLib.length)]
//examLib[exam.count]; // Закешировался setTimeout // getRandomNoteNumbers(3,scale);
setEmaxNotes(notes);
setEmaxStage('listen');
playEmaxNotes(notes)
}
const isTestComplite = () =>{
const exam = examRef.current;
console.log(exam.guessed) // Тоже блядь закешировалось!
return exam.guessed.every(e=>e)
}
// EXAM ===========================================================
// ACTION ===========================================================
// Время в миллисекундах, которое каждая нота занимает в файле
const NOTE_DURATION_MS = 2180; // Например, 500ms для каждой ноты
const playNote = (noteIndex) => {
const audio = new Audio(audioFilePath);
if (noteIndex !== undefined) {
// Устанавливаем время начала проигрывания
audio.currentTime = noteIndex * NOTE_DURATION_MS / 1000; // переводим в секундах
audio.play().catch(err => console.error('Error playing audio:', err));
// Останавливаем звук через 500 мс
setTimeout(() => {
audio.pause();
audio.currentTime = 0; // Сбрасываем текущее время для последующего воспроизведения
}, NOTE_DURATION_MS);
} else {
console.error('Invalid note:', noteIndex);
}
}
const pressKey = (noteIndex) => {
const exam = examRef.current;
testNote(noteIndex);
setPressed(prev => [...prev,noteIndex])
playNote(noteIndex)
//recordNotes(noteIndex)
}
const removeFromPressed = (note) => { setPressed( prev => prev.filter(key=>key!=note) ) }
// RECORD
const [recorded,setRecorded] = useState([])
const recordNotes = (noteIndex,max=3) => {
if(recorded.length){
const last = recorded[recorded.length-1];
console.log(last)
if(last.length>=max){
setRecorded(prev=>[...prev,[noteIndex]])
}else{
setRecorded( [...recorded.slice(0,-1), [...last, noteIndex] ])
}
console.log(recorded)
return false
}
setRecorded([[noteIndex]])
}
// Библиотека ключей в октаве
const defKeys = [
{
name:'C',
val:'C1',
index:0,
},
{
name:'C#',
val:'C1#',
index:1,
black:true,
},
{
name:'D',
index:2,
val:'D1',
},
{
name:'D#',
val:'D1#',
index:3,
black:true,
},
{
name:'E',
val:'E1',
index:4,
},
{
name:'F',
val:'F1',
index:5,
},
{
name:'F#',
val:'F1#',
index:6,
black:true,
},
{
name:'G',
val:'G1',
index:7,
},
{
name:'G#',
val:'G1#',
index:8,
black:true,
},
{
name:'A',
val:'A1',
index:9,
},
{
name:'A#',
val:'A1#',
index:10,
black:true,
},
{
name:'B',
val:'B1',
index:11,
},
{
name:'C',
val:'C2',
index:12,
},
{
name:'C#',
val:'C2#',
black:true,
},
{
name:'D',
val:'D2',
},
{
name:'D#',
val:'D2#',
black:true,
},
{
name:'E',
val:'E2',
},
{
name:'F',
val:'F2',
},
{
name:'F#',
val:'F2#',
black:true,
},
{
name:'G',
val:'G2',
},
{
name:'G#',
val:'G2#',
black:true,
},
{
name:'A',
val:'A2',
},
{
name:'A#',
val:'A2#',
black:true,
},
{
name:'B',
val:'B2',
},
]
const keys = useMemo(()=>{
return defKeys.slice(0,12)
},[])
// MIDI KEYBOARD
const midiKeyNumberToNote = {
60:'C',
62:'D',
64:'E',
65:'F',
}
const [midiAccess, setMidiAccess] = useState(null);
const [inputs, setInputs] = useState([]);
useEffect(() => {
// Запрашиваем доступ к MIDI-устройствам
const requestMIDI = async () => {
if (navigator.requestMIDIAccess) {
const access = await navigator.requestMIDIAccess();
setMidiAccess(access);
} else {
console.error('Web MIDI API not supported in this browser.');
}
};
requestMIDI();
}, []);
useEffect(() => {
if (midiAccess) {
const inputs = Array.from(midiAccess.inputs.values());
setInputs(inputs);
// Обработчик нажатий клавиш
const handleMidiMessage = (event) => {
const [status, note, velocity] = event.data;
if(note<60 || note >= 60 + keys.length ) return false;
const octave = Math.floor((note-60)/12);
const noteIndex = (note-60)%12;
//const noteName = keys[noteNumberInOctave+(12*octave)].val;
if (status === 146) { // Note on
//console.log(`Note on: ${note} (Velocity: ${velocity})`);
pressKey(noteIndex)
} else if (status === 130) { // Note off
removeFromPressed(noteIndex)
}
};
// Подписываемся на все входные MIDI-устройства
inputs.forEach(input => { input.onmidimessage = handleMidiMessage; });
// Удаляем обработчики на каждом обновлении
return () => {
inputs.forEach(input => {
input.onmidimessage = null;
});
};
}
}, [midiAccess, exam, recorded]);
useEffect(()=>{ examRef.current = exam },[exam])
return (
<Flex fullWidth center className={styles.root}>
<Flex column>
<Flex>
{recorded.join``}
</Flex>
{/* <div className={styles.editor}>
{
whiteKeys.map((row,index)=>{
return <Flex gap='0' className={styles.row} key={index}>
{
Array.from({length:editor.columns-1}).map((key,index)=>{
return <div key={index} className={styles.field}>
{ !index && <Flex className={styles.title}>{row.name}</Flex> }
<div className={styles.note}></div>
</div>
})
}
</Flex>
})
}
</div> */}
<div className='xtac xmb120' style={{height:'100px',width:500}}>
<p className='xfs18'>{exam.stage} {exam.count}</p>
{
exam.notes.length>0 &&
<Flex center gap='10' className='xpt40'>
{
exam.notes.map((note,index)=>{
return <Flex gap='0' key={index} className='xfs52'>
<IoMdMusicalNote />
{
index>0 && exam.notes[index-1]!==note
? exam.notes[index-1]<note
? <FaLongArrowAltUp className='xfs12' />
: <FaLongArrowAltDown className='xfs12' />
:false
}
{ exam.guessed[index]!==undefined?
exam.guessed[index]
? <div className='xfs12' style={{ width:'100%'}}>
<div style={{background:'green', height:'3px', width:'100%'}}></div>
{keys[note].val}
</div>
: <div style={{background:'red', height:'3px', width:'100%'}}></div>
: false
}
</Flex>
})
}
</Flex>
}
</div>
<Flex className='xmb120'>
{exam.notes.length>0
? <button onClick={e=>playEmaxNotes(exam.notes)}>REPEAT</button>
: <button onClick={startTest}>START</button>
}
</Flex>
<Flex gap='2' top className={styles.keys_container}>
{
keys.map((key)=>{
return <div
key={`${key.val}`}
className={`${key.black ? styles.black_key : styles.white_key} ${pressed.includes(key.index)?styles.pressed:''}`}
onMouseUp={e=>removeFromPressed(key.index)}
onMouseDown={e=>pressKey(key.index)}
>
<div className={styles.name}>{key.name}</div>
</div>
})
}
</Flex>
</Flex>
</Flex>
)
}
export default Piano
Опитимизуй код