Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try using smplr #24

Draft
wants to merge 2 commits into
base: stable
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"@tauri-apps/api": "^1.1.0",
"date-fns": "^2.29.3",
"fuse.js": "^6.6.2",
"midicube": "^0.6.2",
"smplr": "^0.12.2",
"ua-parser-js": "^1.0.32",
"uuid": "^9.0.0",
"vue": "^3.2.37"
Expand Down
42 changes: 20 additions & 22 deletions src/utils/midi.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { tauri } from '@tauri-apps/api'

import * as MIDI from 'midicube'
import { Soundfont } from "smplr";
import { convertFileSrc } from '@tauri-apps/api/tauri'

;(window as any).MIDI = MIDI
const context = new AudioContext();
const soundfontUrl = convertFileSrc('', 'midi')

const loadedInstruments = new Set<string>()
const loadedInstruments = new Map<string, Soundfont>()

export interface MidiNote {
sync: boolean
Expand All @@ -16,38 +17,35 @@ export interface MidiNote {
volume: number
}

function loadInstrument(instrument: string): Promise<boolean> {
const soundfontUrl = convertFileSrc('', 'midi')
async function loadInstrument(instrument: string): Promise<void> {
const sf = new Soundfont(context, {
volumeToGain: (volume: number) => volume,
instrumentUrl: `${soundfontUrl}/${instrument}-mp3.js`
});

return new Promise((resolve) => {
MIDI.loadPlugin({
instrument,
soundfontUrl,
targetFormat: 'mp3',
onerror: () => resolve(false),
onsuccess: () => {
loadedInstruments.add(instrument)
loadedInstruments.set(instrument, sf);

resolve(true)
},
})
})
await sf.load;
}

export async function playNote(note: MidiNote) {
const wake = async () => await tauri.invoke('wake_sync')

if (!loadedInstruments.has(note.name)) {
if (!(await loadInstrument(note.name))) {
try {
await loadInstrument(note.name)
} catch (e) {
return await wake()
}
}

const sf = loadedInstruments.get(note.name)
if (note.duration > 0) {
MIDI.setVolume(0, note.volume)
MIDI.programChange(0, note.instrument)
MIDI.noteOn(0, note.note, 127, 0)
MIDI.noteOff(0, note.note, note.duration)
sf?.start({
note: note.note,
duration: note.duration,
velocity: note.volume / 20 + 2,
})
}

if (note.sync) {
Expand Down