function createMelody()

in src/components/CoconetPlayer.tsx [45:90]


function createMelody({
  startDigit,
  instrument,
  bpm = defaultBpm,
  scale,
  length,
}: MelodyParameters): Promise<mm.INoteSequence> {
  const q = 4;
  return Promise.all([
    pi.get(startDigit % (pi.length - length + 1), length),
    import("@magenta/music/esm/protobuf"),
  ])
    .then(([digits, mmp]) => {
      const notes = new Array<mm.NoteSequence.Note>();
      for (let i = 0; i < digits.length; i++) {
        const d = parseInt(digits[i]);
        const scaleNote = Music.scales.get(scale)![d];
        const midiNote = noteMidi(scaleNote);
        notes.push(
          mmp.NoteSequence.Note.create({
            pitch: midiNote,
            quantizedStartStep: i * q,
            quantizedEndStep: (i + 1) * q,
            instrument: 0,
            program: instrument,
            velocity: 80,
          })
        );
      }
      const melody = mmp.NoteSequence.create({
        notes: notes,
        quantizationInfo: { stepsPerQuarter: 4 },
        totalQuantizedSteps: digits.length * q,
        tempos: [
          mmp.NoteSequence.Tempo.create({
            time: 0,
            qpm: bpm,
          }),
        ],
      });
      return melody;
    })
    .catch(() => {
      throw new Error("melody generation error (pi api unreachable?)");
    });
}