MidiWriterJS 是一个 JavaScript 库,用于编程生成和创建多轨道表达式丰富的 MIDI 文件和 JSON。
以下是一个完整的示例,演示如何使用JavaScript和MidiWriterJS生成一个简单的MIDI音乐文件:
步骤概览引入MidiWriterJS库。创建MIDI音轨和事件。生成并下载MIDI文件。完整示例代码<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> </head> <body> <script type="module"> import midiWriterJs from "https://cdn.skypack.dev/midi-writer-js@2.1.4"; const track = new midiWriterJs.Track(); // Add a tempo event track.setTempo(120); // Add a time signature event track.setTimeSignature(4, 4); // Add a note (C4, duration of 4 beats) const note = new midiWriterJs.NoteEvent({pitch: ['C4'], duration: '4'}); track.addEvent(note); // Generate MIDI file and create a download link const write = new midiWriterJs.Writer(track); const blob = new Blob([write.buildFile()], { type: 'audio/midi' }); const url = URL.createObjectURL(blob); // Create a download link and click it const link = document.createElement('a'); link.href = url; link.download = 'music.mid'; link.click(); // Revoke the object URL after the download URL.revokeObjectURL(url); </script> </body> </html>解释
引入MidiWriterJS库:
在HTML中引入MidiWriterJS库的CDN。创建MIDI音轨和事件:
使用MidiWriter.Track创建一个新的MIDI音轨。设置音轨的速度(BPM)和时间签名。添加一个音符事件,这里添加了一个C4音符,持续时间为4拍。生成并下载MIDI文件:
使用MidiWriter.Writer生成MIDI文件。创建一个Blob对象并生成一个下载链接。模拟点击下载链接以下载生成的MIDI文件。在下载后撤销对象URL以释放内存。https://github.com/grimmdude/MidiWriterJS
网友回复