如何编写音符半音移调函数?吉他调音应用开发求助
半音移调函数的修复方案
原代码存在的问题
- 参数定义和调用不匹配:示例里函数接收的是
{note, octave}对象,但你的函数把note、octave拆成了两个独立参数,调用时会直接导致参数错位。 - 索引越界未处理:向上移调时,当原索引是数组最后一位(比如
G#对应索引11),newIndex会变成12,这时候取musicalNotes[12]会得到undefined,原代码只处理了索引为负的情况,没覆盖索引超出上限的场景。 - 八度计算逻辑错误:原公式在处理
G#向上移这类场景时,无法正确触发八度加1的逻辑。
修复后的代码
function pitchShiftNoteByHalfStep(pitch, direction) { const musicalNotes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']; const noteIndex = musicalNotes.indexOf(pitch.note); // 计算新索引,用取模处理循环,确保索引始终在0-11范围内 const step = direction === 'up' ? 1 : -1; let newIndex = noteIndex + step; // 处理负数索引的取模兼容(JS中负数取模结果为负,需调整为正索引) newIndex = (newIndex + 12) % 12; // 计算新八度:向上移到数组末尾时升八度,向下移到数组开头时降八度 let newOctave = pitch.octave; if (direction === 'up' && noteIndex === 11) { newOctave += 1; } else if (direction === 'down' && noteIndex === 0) { newOctave -= 1; } return { note: musicalNotes[newIndex], octave: newOctave }; }
测试示例用例
// 测试用例1:B3向上移半音 const noteShiftedHalfStepUp = pitchShiftNoteByHalfStep({note: "B", octave: 3}, "up") console.log(noteShiftedHalfStepUp) // {note: "C", octave: 4} ✅ // 测试用例2:G#4向上移半音 const testCase2 = pitchShiftNoteByHalfStep({note:"G#", octave: 4}, "up") console.log(testCase2) // {note: "A", octave: 4} ✅ // 测试用例3:A#4向下移半音 const testCase3 = pitchShiftNoteByHalfStep({note: "A#", octave: 4}, "down") console.log(testCase3) // {note: "A", octave: 4} ✅ // 额外边界测试:C0向下移半音 const testCase4 = pitchShiftNoteByHalfStep({note: "C", octave: 0}, "down") console.log(testCase4) // {note: "B", octave: -1} ✅
关键修复点说明
- 参数对齐:调整函数参数为
pitch对象(包含note和octave)和direction,和示例调用逻辑保持一致。 - 索引循环处理:用
(newIndex + 12) % 12确保无论上下移调,索引都能正确循环到数组的起始或结尾,彻底解决越界问题。 - 八度逻辑简化:直接判断边界场景——向上移到数组末尾时升八度,向下移到数组开头时降八度,逻辑清晰且结果准确。
内容的提问来源于stack exchange,提问作者Ryan Roberts
相关产品推荐
相关产品推荐

