Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[submodule "wasm-src/lib/ymfm"]
path = wasm-src/lib/ymfm
url = https://github.com/aaronsgiles/ymfm.git
[submodule "wasm-src/lib/miniaudio"]
path = wasm-src/lib/miniaudio
url = https://github.com/mackron/miniaudio.git
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Rerrah

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# OPNShare

Web app to share and explore instruments for OPN-family FM sounds.

This app uses these libraries:

- [ymfm](https://github.com/aaronsgiles/ymfm) - Copyright (c) 2021 Aaron Giles, under BSD 3-Clause License
- [miniaudio](https://github.com/mackron/miniaudio) - Copyright 2025 David Reid, under MIT License
260 changes: 209 additions & 51 deletions app/instrument/[id]/components/audio-preview.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,150 @@
"use client";

import type React from "react";
import { useState } from "react";
import { useEffect, useRef, useState } from "react";
import { FaVolumeUp } from "react-icons/fa";
import { Label } from "recharts";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useFmSynthesizer } from "@/contexts/synth";
import type { FmInstrument } from "@/features/instrument/types";
import { AVAILABLE_CHIPS } from "@/features/preview/consts";
import { clampOctave, withinOctave } from "@/features/preview/octave";
import { type Pitch, pitchToString } from "@/features/preview/pitch";
import type { AvailableChip } from "@/features/preview/types";
import { iota } from "@/utils/range";

export function AudioPreview(): React.JSX.Element {
const [playbackChip, setPlaybackChip] = useState("OPL3");
const [octaveOffset, setOctaveOffset] = useState<number>(0);
const DISPLAYED_OCTAVE_RANGE = 4;
const DISPLAYED_WHITE_KEY_COUNT = 7 * DISPLAYED_OCTAVE_RANGE;
const WHITE_NOTE_TABLE = [0, 2, 4, 5, 7, 9, 11] as const;
const BLACK_NOTE_NAME_MAP: ReadonlyMap<number, number> = new Map([
[0, 1],
[1, 3],
[3, 6],
[4, 8],
[5, 10],
]);

const chips = ["OPL3", "OPN2", "OPM", "OPL2"];
type ActiveKey = {
pitch: Pitch;
keyId: string;
};

export function AudioPreview({
instrument,
}: {
instrument: FmInstrument;
}): React.JSX.Element {
const [playbackChip, setPlaybackChip] = useState<AvailableChip>("OPNA");
const [octaveOffset, setOctaveOffset] = useState<number>(3);

// Key: pointerId, Value: ActiveNote
const activeNotes = useRef<Map<number, ActiveKey>>(new Map());

// For pressed button color.
const [pressedKeys, setPressedKeys] = useState<Set<string>>(new Set());

const synthContext = useFmSynthesizer();

// Set an instrument on loading this component.
useEffect(() => {
synthContext?.setInstrument(instrument);
}, [instrument, synthContext]);

// Reset synthesizer on unmount this component and jump to the different
// page.
useEffect(() => {
return () => {
synthContext?.reset();
};
}, [synthContext]);

async function noteOn(pitch: Pitch, pointerId: number) {
await synthContext?.keyOn(pitch, pointerId);
}

async function noteOff(pointerId: number) {
synthContext?.keyOff(pointerId);
}

async function handlePointerDown(
e: React.PointerEvent<HTMLButtonElement>,
pitch: Pitch,
keyId: string
) {
if (e.pointerType === "mouse" && e.button !== 0) {
// Ignore mouse buttons other than the left button.
return;
}

activeNotes.current.set(e.pointerId, { pitch, keyId });
setPressedKeys((prev) => new Set(prev).add(keyId));
await noteOn(pitch, e.pointerId);
}

async function handlePointerUp(e: React.PointerEvent<HTMLButtonElement>) {
const active = activeNotes.current.get(e.pointerId);
if (active) {
await noteOff(e.pointerId);
activeNotes.current.delete(e.pointerId);
setPressedKeys((prev) => {
const next = new Set(prev);
next.delete(active.keyId);
return next;
});
}
}

async function handlePointerEnter(
e: React.PointerEvent<HTMLButtonElement>,
pitch: Pitch,
keyId: string
) {
const active = activeNotes.current.get(e.pointerId);
if (active) {
if (
active.pitch.octave === pitch.octave &&
active.pitch.semitone === pitch.semitone
) {
return;
}

// Note off previous pressed note.
await noteOff(e.pointerId);
setPressedKeys((prev) => {
const next = new Set(prev);
next.delete(active.keyId);
next.add(keyId);
return next;
});

// Note on new one.
activeNotes.current.set(e.pointerId, {
pitch,
keyId,
});
await noteOn(pitch, e.pointerId);
}
}

function handlePointerLeave(
_e: React.PointerEvent<HTMLButtonElement>,
keyId: string
) {
// Only change button color and keep activeNotes.
setPressedKeys((prev) => {
const next = new Set(prev);
next.delete(keyId);
return next;
});
}

return (
<Card>
Expand All @@ -33,12 +159,15 @@ export function AudioPreview(): React.JSX.Element {
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<Label className="text-sm font-medium">Chip:</Label>
<Select value={playbackChip} onValueChange={setPlaybackChip}>
<Select
value={playbackChip}
onValueChange={(chip) => setPlaybackChip(chip as AvailableChip)}
>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
{chips.map((chip) => (
{AVAILABLE_CHIPS.map((chip) => (
<SelectItem key={chip} value={chip}>
{chip}
</SelectItem>
Expand All @@ -51,80 +180,109 @@ export function AudioPreview(): React.JSX.Element {
<Button
variant="outline"
size="sm"
onClick={() => setOctaveOffset(Math.max(-1, octaveOffset - 1))}
disabled={octaveOffset <= -1}
onClick={() => setOctaveOffset((prev) => clampOctave(prev - 1))}
disabled={!withinOctave(octaveOffset)}
>
←
</Button>
<span className="text-sm font-mono w-8 text-center">
{octaveOffset >= 0 ? `+${octaveOffset}` : octaveOffset}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setOctaveOffset(Math.min(8, octaveOffset + 1))}
disabled={octaveOffset >= 8}
onClick={() =>
setOctaveOffset(
(prev) =>
clampOctave(prev + DISPLAYED_OCTAVE_RANGE) -
DISPLAYED_OCTAVE_RANGE +
1
)
}
disabled={!withinOctave(octaveOffset)}
>
→
</Button>
</div>
</div>

{/* Piano Keyboard - 4 octaves */}
{/* Piano Keyboard */}
<div className="bg-muted rounded-lg p-4">
<div className="flex justify-center">
<div className="relative">
{/* White keys */}
<div className="flex">
{Array.from({ length: 28 }).map((_, i) => {
{[...iota(DISPLAYED_WHITE_KEY_COUNT)].map((i) => {
const whiteKeyIndex = i % 7;
const octave = Math.floor(i / 7);
const notes = ["C", "D", "E", "F", "G", "A", "B"];
const note = notes[whiteKeyIndex];
const actualOctave = octave + 2 + octaveOffset;
const relativeOctave = Math.floor(i / 7);
const octave = relativeOctave + octaveOffset;
const semitone = WHITE_NOTE_TABLE[whiteKeyIndex];
const pitch: Pitch = { octave, semitone };
const pitchName = pitchToString(pitch);
const isPressed = pressedKeys.has(pitchName);

return (
<button
key={i}
className="bg-white border border-gray-300 w-6 h-16 hover:bg-gray-100 transition-colors relative"
onClick={() => {
/* Play note */
}}
key={pitchName}
type="button"
className={`w-6 h-16 border border-gray-300 relative transition-colors ${
isPressed
? "bg-blue-300"
: "bg-white hover:bg-gray-100"
}`}
onPointerDown={(e) =>
handlePointerDown(e, pitch, pitchName)
}
onPointerUp={handlePointerUp}
onPointerEnter={(e) =>
handlePointerEnter(e, pitch, pitchName)
}
onPointerLeave={(e) => handlePointerLeave(e, pitchName)}
>
<span className="text-xs text-gray-600 absolute bottom-1 left-1/2 transform -translate-x-1/2">
{note}
{actualOctave}
<span className="text-xs text-gray-600 select-none absolute bottom-1 left-1/2 transform -translate-x-1/2">
{pitchName}
</span>
</button>
);
})}
</div>

{/* Black keys */}
<div className="absolute top-0 flex">
{Array.from({ length: 28 }).map((_, i) => {
{[...iota(DISPLAYED_WHITE_KEY_COUNT)].map((i) => {
const whiteKeyIndex = i % 7;
const octave = Math.floor(i / 7);
if ([0, 1, 3, 4, 5].includes(whiteKeyIndex)) {
const blackNotes = ["C#", "D#", "", "F#", "G#", "A#"];
const blackNote = blackNotes[whiteKeyIndex];
const actualOctave = octave + 2 + octaveOffset;
return (
<button
key={`black-${i}`}
className="bg-gray-800 w-4 h-10 hover:bg-gray-700 transition-colors relative -ml-2 z-10"
style={{ marginLeft: i === 0 ? "16px" : "8px" }}
onClick={() => {
/* Play black note */
}}
>
<span className="text-xs text-white absolute bottom-1 left-1/2 transform -translate-x-1/2">
{blackNote}
{actualOctave}
</span>
</button>
);
} else {
const semitone = BLACK_NOTE_NAME_MAP.get(whiteKeyIndex);
if (!semitone) {
return <div key={`spacer-${i}`} className="w-6" />;
}

const relativeOctave = Math.floor(i / 7);
const octave = relativeOctave + octaveOffset;
const pitch: Pitch = { octave, semitone };
const pitchName = pitchToString(pitch);
const isPressed = pressedKeys.has(pitchName);

return (
<button
key={pitchName}
type="button"
className={`w-4 h-10 relative -ml-2 z-10 transition-colors ${
isPressed
? "bg-blue-600"
: "bg-gray-800 hover:bg-gray-700"
}`}
style={{ marginLeft: i === 0 ? "16px" : "8px" }}
onPointerDown={(e) =>
handlePointerDown(e, pitch, pitchName)
}
onPointerUp={handlePointerUp}
onPointerEnter={(e) =>
handlePointerEnter(e, pitch, pitchName)
}
onPointerLeave={(e) => handlePointerLeave(e, pitchName)}
>
<span className="text-xs text-white select-none absolute bottom-1 left-1/2 transform -translate-x-1/2">
{pitchName}
</span>
</button>
);
})}
</div>
</div>
Expand Down
5 changes: 2 additions & 3 deletions app/instrument/[id]/components/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,12 @@ import type {
import type { FmInstrument, FmOperator } from "@/features/instrument/types";
import { useAuthUserId } from "@/stores/auth";
import { isoStringToLocaleString } from "@/utils/date";
import { AudioPreview } from "./audio-preview";
import { DeleteDialog } from "./delete-dialog";
import { InfoEditDialog } from "./info-edit-dialog";
import { LikeButton } from "./like-button";
import { TextExportDialog } from "./text-export-dialog";

// import { AudioPreview } from "./components/audio-preview";

function downloadFile(file: File) {
const url = URL.createObjectURL(file);
const a = document.createElement("a");
Expand Down Expand Up @@ -283,7 +282,7 @@ export function InstrumentDetailContent({
</Card>

{/* Audio Player */}
{/* <AudioPreview /> */}
<AudioPreview instrument={instrument} />

{/* Parameters Section */}
<Card>
Expand Down
Loading