Compare commits
9 Commits
a8cc20f041
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| cfcfa0ccee | |||
| 3f41d7699c | |||
| 6a4be6b939 | |||
| 0c35693598 | |||
| 2dd604192f | |||
| fb19efa72f | |||
| 05c4f19109 | |||
| 19d7a161c7 | |||
| e158467c76 |
@@ -35,6 +35,10 @@ yarn-error.log*
|
|||||||
/data/*.db-wal
|
/data/*.db-wal
|
||||||
/data/*.db-shm
|
/data/*.db-shm
|
||||||
|
|
||||||
|
# uploads (user content)
|
||||||
|
/public/uploads/
|
||||||
|
/data/uploads/
|
||||||
|
|
||||||
# env files (can opt-in for committing if needed)
|
# env files (can opt-in for committing if needed)
|
||||||
.env*
|
.env*
|
||||||
|
|
||||||
|
|||||||
+3
-2
@@ -13,14 +13,15 @@ WORKDIR /app
|
|||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
ENV NEXT_TELEMETRY_DISABLED=1
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
|
||||||
RUN addgroup --system --gid 1001 nodejs && \
|
RUN apk add --no-cache ffmpeg && \
|
||||||
|
addgroup --system --gid 1001 nodejs && \
|
||||||
adduser --system --uid 1001 nextjs
|
adduser --system --uid 1001 nextjs
|
||||||
|
|
||||||
COPY --from=builder /app/public ./public
|
COPY --from=builder /app/public ./public
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||||
|
|
||||||
RUN mkdir -p /app/data /app/public/uploads && chmod 777 /app/data /app/public/uploads
|
RUN mkdir -p /app/data /app/data/uploads && chmod 777 /app/data /app/data/uploads
|
||||||
|
|
||||||
USER nextjs
|
USER nextjs
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import path from "path";
|
|||||||
import { v4 as uuidv4 } from "uuid";
|
import { v4 as uuidv4 } from "uuid";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
|
|
||||||
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "images");
|
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "images");
|
||||||
|
|
||||||
const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
|
const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
|
||||||
const MAX_SIZE = 5 * 1024 * 1024;
|
const MAX_SIZE = 5 * 1024 * 1024;
|
||||||
|
|||||||
+24
-12
@@ -6,8 +6,13 @@ import { writeFile, mkdir, unlink } from "fs/promises";
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
import { v4 as uuidv4 } from "uuid";
|
import { v4 as uuidv4 } from "uuid";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
|
import { convertToCompressedMp3 } from "@/lib/convert";
|
||||||
|
|
||||||
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "sounds");
|
export const maxDuration = 120;
|
||||||
|
|
||||||
|
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "sounds");
|
||||||
|
const ALLOWED_EXTENSIONS = /\.(mp3|ogg|wav|flac|aac|m4a|wma|opus|webm|mp4|avi|mov|mkv|webm|wmv|flv)$/i;
|
||||||
|
const MAX_SIZE = 50 * 1024 * 1024; // 50 MB
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const session = await getServerSession();
|
const session = await getServerSession();
|
||||||
@@ -42,29 +47,36 @@ export async function POST(req: NextRequest) {
|
|||||||
const results: { url: string; originalName: string; duration: number }[] = [];
|
const results: { url: string; originalName: string; duration: number }[] = [];
|
||||||
|
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
if (!file.name.toLowerCase().endsWith(".ogg")) continue;
|
if (!ALLOWED_EXTENSIONS.test(file.name)) continue;
|
||||||
if (file.size > 2 * 1024 * 1024) continue;
|
if (file.size > MAX_SIZE) continue;
|
||||||
|
|
||||||
|
const baseName = uuidv4();
|
||||||
|
const inputPath = path.join(UPLOAD_DIR, `${baseName}.in`);
|
||||||
|
const mp3Path = path.join(UPLOAD_DIR, `${baseName}.mp3`);
|
||||||
|
|
||||||
const ext = path.extname(file.name);
|
|
||||||
const filename = `${uuidv4()}${ext}`;
|
|
||||||
const filepath = path.join(UPLOAD_DIR, filename);
|
|
||||||
const bytes = await file.arrayBuffer();
|
const bytes = await file.arrayBuffer();
|
||||||
await writeFile(filepath, Buffer.from(bytes));
|
await writeFile(inputPath, Buffer.from(bytes));
|
||||||
|
|
||||||
// compute duration from file size (approximate for OGG Vorbis ~64kbps)
|
let storedFilename: string;
|
||||||
const duration = Math.round((file.size / (64 * 128)) * 10) / 10;
|
if (convertToCompressedMp3(inputPath, mp3Path)) {
|
||||||
|
await unlink(inputPath).catch(() => {});
|
||||||
|
storedFilename = `${baseName}.mp3`;
|
||||||
|
} else {
|
||||||
|
await unlink(inputPath).catch(() => {});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
const id = uuidv4();
|
const id = uuidv4();
|
||||||
db.insert(sounds).values({
|
db.insert(sounds).values({
|
||||||
id,
|
id,
|
||||||
originalName: file.name,
|
originalName: file.name,
|
||||||
storedFilename: filename,
|
storedFilename,
|
||||||
duration: Math.min(duration, 6),
|
duration: 6,
|
||||||
uploadedBy: session.id,
|
uploadedBy: session.id,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
}).run();
|
}).run();
|
||||||
|
|
||||||
results.push({ url: `/uploads/sounds/${filename}`, originalName: file.name, duration: Math.min(duration, 6) });
|
results.push({ url: `/uploads/sounds/${storedFilename}`, originalName: file.name, duration: 6 });
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ sounds: results });
|
return NextResponse.json({ sounds: results });
|
||||||
|
|||||||
@@ -2,11 +2,16 @@ import { NextRequest, NextResponse } from "next/server";
|
|||||||
import { getServerSession } from "@/lib/auth";
|
import { getServerSession } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { sounds } from "@/lib/db/schema";
|
import { sounds } from "@/lib/db/schema";
|
||||||
import { writeFile, mkdir } from "fs/promises";
|
import { writeFile, mkdir, unlink } from "fs/promises";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { v4 as uuidv4 } from "uuid";
|
import { v4 as uuidv4 } from "uuid";
|
||||||
|
import { convertToCompressedMp3 } from "@/lib/convert";
|
||||||
|
|
||||||
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "sounds");
|
export const maxDuration = 60;
|
||||||
|
|
||||||
|
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "sounds");
|
||||||
|
const ALLOWED_EXTENSIONS = /\.(mp3|ogg|wav|flac|aac|m4a|wma|opus|webm|mp4|avi|mov|mkv|webm|wmv|flv)$/i;
|
||||||
|
const MAX_SIZE = 50 * 1024 * 1024; // 50 MB
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
const session = await getServerSession();
|
const session = await getServerSession();
|
||||||
@@ -19,35 +24,43 @@ export async function POST(req: NextRequest) {
|
|||||||
const file = formData.get("file") as File | null;
|
const file = formData.get("file") as File | null;
|
||||||
if (!file) return NextResponse.json({ error: "No file" }, { status: 400 });
|
if (!file) return NextResponse.json({ error: "No file" }, { status: 400 });
|
||||||
|
|
||||||
if (!file.name.toLowerCase().endsWith(".ogg")) {
|
if (!ALLOWED_EXTENSIONS.test(file.name)) {
|
||||||
return NextResponse.json({ error: "Only OGG files allowed" }, { status: 400 });
|
return NextResponse.json({ error: "Unsupported file format" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (file.size > 2 * 1024 * 1024) {
|
if (file.size > MAX_SIZE) {
|
||||||
return NextResponse.json({ error: "File too large (max 2MB)" }, { status: 400 });
|
return NextResponse.json({ error: "File too large (max 50MB)" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
await mkdir(UPLOAD_DIR, { recursive: true });
|
await mkdir(UPLOAD_DIR, { recursive: true });
|
||||||
const ext = path.extname(file.name);
|
|
||||||
const filename = `${uuidv4()}${ext}`;
|
const baseName = uuidv4();
|
||||||
const filepath = path.join(UPLOAD_DIR, filename);
|
const inputPath = path.join(UPLOAD_DIR, `${baseName}.in`);
|
||||||
|
const mp3Path = path.join(UPLOAD_DIR, `${baseName}.mp3`);
|
||||||
|
|
||||||
const bytes = await file.arrayBuffer();
|
const bytes = await file.arrayBuffer();
|
||||||
await writeFile(filepath, Buffer.from(bytes));
|
await writeFile(inputPath, Buffer.from(bytes));
|
||||||
|
|
||||||
// approximate duration
|
let storedFilename: string;
|
||||||
const duration = Math.round((file.size / (64 * 128)) * 10) / 10;
|
if (convertToCompressedMp3(inputPath, mp3Path)) {
|
||||||
|
await unlink(inputPath).catch(() => {});
|
||||||
|
storedFilename = `${baseName}.mp3`;
|
||||||
|
|
||||||
const id = uuidv4();
|
const id = uuidv4();
|
||||||
db.insert(sounds).values({
|
db.insert(sounds).values({
|
||||||
id,
|
id,
|
||||||
originalName: file.name,
|
originalName: file.name,
|
||||||
storedFilename: filename,
|
storedFilename,
|
||||||
duration: Math.min(duration, 6),
|
duration: 6,
|
||||||
uploadedBy: session.id,
|
uploadedBy: session.id,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
}).run();
|
}).run();
|
||||||
|
|
||||||
return NextResponse.json({ url: `/uploads/sounds/${filename}` });
|
return NextResponse.json({ url: `/uploads/sounds/${storedFilename}` });
|
||||||
|
}
|
||||||
|
|
||||||
|
await unlink(inputPath).catch(() => {});
|
||||||
|
return NextResponse.json({ error: "Conversion failed" }, { status: 500 });
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
|
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import fs from "fs";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
|
const UPLOADS_DIR = path.join(process.cwd(), "data", "uploads");
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
_req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ path: string[] }> }
|
||||||
|
) {
|
||||||
|
const { path: segments } = await params;
|
||||||
|
const filePath = path.join(UPLOADS_DIR, ...segments);
|
||||||
|
|
||||||
|
if (!filePath.startsWith(UPLOADS_DIR)) {
|
||||||
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const content = fs.readFileSync(filePath);
|
||||||
|
const ext = path.extname(filePath).toLowerCase();
|
||||||
|
const mime = MIME_MAP[ext] ?? "application/octet-stream";
|
||||||
|
return new NextResponse(content, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": mime,
|
||||||
|
"Cache-Control": "public, max-age=31536000, immutable",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIME_MAP: Record<string, string> = {
|
||||||
|
".mp3": "audio/mpeg",
|
||||||
|
".ogg": "audio/ogg",
|
||||||
|
".wav": "audio/wav",
|
||||||
|
".flac": "audio/flac",
|
||||||
|
".m4a": "audio/mp4",
|
||||||
|
".webm": "audio/webm",
|
||||||
|
".mp4": "video/mp4",
|
||||||
|
".avi": "video/x-msvideo",
|
||||||
|
".mov": "video/quicktime",
|
||||||
|
".mkv": "video/x-matroska",
|
||||||
|
".png": "image/png",
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".gif": "image/gif",
|
||||||
|
".webp": "image/webp",
|
||||||
|
};
|
||||||
@@ -168,9 +168,9 @@ export function BingoCard({ campaign, initialGrid, currentUserNickname, isAdmin
|
|||||||
captainSanity >= 25 ? "panic" : "lost";
|
captainSanity >= 25 ? "panic" : "lost";
|
||||||
|
|
||||||
const sanityLabel =
|
const sanityLabel =
|
||||||
sanityStage === "calm" ? "Спокоен" :
|
sanityStage === "calm" ? "Держится ещё" :
|
||||||
sanityStage === "nervous" ? "Нервничает" :
|
sanityStage === "nervous" ? "Кукуха свистит" :
|
||||||
sanityStage === "panic" ? "Паника!" : "Кукуха уехала!";
|
sanityStage === "panic" ? "Паника!" : "Кукуха уехала пиздаааа!";
|
||||||
|
|
||||||
const sanityIcon =
|
const sanityIcon =
|
||||||
sanityStage === "calm" ? "😐" :
|
sanityStage === "calm" ? "😐" :
|
||||||
|
|||||||
+69
-65
@@ -5,9 +5,11 @@ import { Card, CardContent } from "./ui/card";
|
|||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
import { Input } from "./ui/input";
|
import { Input } from "./ui/input";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
|
||||||
import { SOUND_CATEGORIES, EMOJIS } from "@/lib/bingo-data";
|
import { SOUND_CATEGORIES } from "@/lib/bingo-data";
|
||||||
import { Badge } from "./ui/badge";
|
import { Badge } from "./ui/badge";
|
||||||
import { ResourceBrowser, DragData } from "./ResourceBrowser";
|
import { ResourceBrowser, DragData } from "./ResourceBrowser";
|
||||||
|
import { playSoundOnce } from "@/lib/sounds";
|
||||||
|
import { SoundPlayerBar } from "./SoundPlayerBar";
|
||||||
|
|
||||||
type Item = {
|
type Item = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -25,43 +27,52 @@ type Campaign = {
|
|||||||
gridSize: number;
|
gridSize: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
function EmojiPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
|
const EMOJI_LIST = [
|
||||||
const [open, setOpen] = useState(false);
|
"😀", "😂", "🤣", "😍", "🥰", "😘", "😊", "😎", "🤩", "🥳", "🤯", "😱",
|
||||||
const ref = useRef<HTMLDivElement>(null);
|
"😈", "🤡", "💀", "👻", "👽", "🤖", "🎃", "😺", "🙈", "🙉", "🙊", "💩",
|
||||||
|
"🔥", "🌊", "💥", "💫", "⭐", "🌟", "✨", "⚡", "☄️", "💧", "🧊", "🌋",
|
||||||
|
"🎉", "🎊", "🎈", "🎁", "🏆", "🥇", "💎", "🔮", "🪄", "🧨", "🔫", "⚔️",
|
||||||
|
"🛡️", "🚀", "🛸", "🚁", "⚓", "🌀", "🌈", "🌪️", "☢️", "☣️", "⚕️", "🧬",
|
||||||
|
"💉", "💊", "🩸", "🧪", "🔬", "🔭", "📡", "🎯", "🎲", "♟️", "🧩", "🎭",
|
||||||
|
"🎵", "🎶", "🎺", "📯", "🔔", "🎤", "🎧", "📢", "📣", "🔊", "🔇", "💤",
|
||||||
|
"💣", "🔪", "🪦", "⚰️", "🪤", "🧲", "🗝️", "🔑", "🔓", "🔒", "🛠️", "⛓️",
|
||||||
|
"🧹", "🪠", "🔧", "⚙️", "📦", "📀", "💿", "📹", "📸", "📷", "🖼️", "🎨",
|
||||||
|
"🍺", "🍻", "🍷", "🥃", "🍸", "🍹", "🧉", "🍕", "🍔", "🌭", "🍿", "🧀",
|
||||||
|
"🥜", "🌶️", "🍄", "🥚", "🧅", "🥕", "🥦", "🫁", "🧠", "👀", "👁️", "🫀",
|
||||||
|
"💋", "🫂", "🤝", "👍", "👎", "👊", "✊", "🤛", "🤜", "👆", "👇", "🖕",
|
||||||
|
"💪", "🦵", "🦶", "👂", "👃", "🧑🚀", "🧑🔧", "🧑⚕️", "🧑✈️", "🧑🏫", "🧑🎤", "🧑🍳",
|
||||||
|
"🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨", "🐯", "🦁", "🐮",
|
||||||
|
"🦈", "🐙", "🦑", "🐋", "🐬", "🦭", "🐊", "🦎", "🐍", "🐢", "🦖", "🦕",
|
||||||
|
"🦟", "🦗", "🐛", "🪱", "🦋", "🐌", "🐞", "🐜", "🦂", "🕷️", "🦀", "🪸",
|
||||||
|
];
|
||||||
|
|
||||||
useEffect(() => {
|
function EmojiPickerGrid({ value, onChange }: { value: string; onChange: (v: string) => void }) {
|
||||||
function handleClick(e: MouseEvent) {
|
const [search, setSearch] = useState("");
|
||||||
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
|
const filtered = search ? EMOJI_LIST.filter(e => e.includes(search)) : EMOJI_LIST;
|
||||||
}
|
|
||||||
document.addEventListener("mousedown", handleClick);
|
|
||||||
return () => document.removeEventListener("mousedown", handleClick);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="relative">
|
<div className="space-y-2">
|
||||||
<button
|
<input
|
||||||
type="button"
|
type="text"
|
||||||
onClick={() => setOpen(!open)}
|
placeholder="Search emoji..."
|
||||||
className="w-10 h-10 flex items-center justify-center text-xl rounded border border-slate-700/50 bg-slate-800/50 hover:bg-slate-700/50 cursor-pointer"
|
value={search}
|
||||||
>
|
onChange={e => setSearch(e.target.value)}
|
||||||
{value || "?"}
|
className="w-full bg-slate-800/60 border border-slate-700/30 rounded px-2 py-1 text-[10px] font-mono text-slate-200 placeholder:text-slate-600 outline-none focus:border-cyan-500/50"
|
||||||
</button>
|
/>
|
||||||
{open && (
|
<div className="flex flex-wrap gap-1 max-h-36 overflow-y-auto">
|
||||||
<div className="absolute top-full left-0 mt-1 z-50 bg-slate-900 border border-slate-700/50 rounded-lg p-2 shadow-xl w-[280px]">
|
{filtered.map(e => (
|
||||||
<div className="grid grid-cols-8 gap-1">
|
<button
|
||||||
{EMOJIS.map(e => (
|
key={e}
|
||||||
<button
|
type="button"
|
||||||
key={e}
|
onClick={() => onChange(e)}
|
||||||
type="button"
|
className={`w-7 h-7 flex items-center justify-center text-sm rounded hover:bg-slate-700/60 cursor-pointer active:scale-90 transition-transform ${
|
||||||
onClick={() => { onChange(e); setOpen(false); }}
|
e === value ? "bg-cyan-700/50 ring-1 ring-cyan-400" : ""
|
||||||
className={`w-8 h-8 flex items-center justify-center text-base rounded hover:bg-slate-700 cursor-pointer ${e === value ? "bg-cyan-700/50 ring-1 ring-cyan-400" : ""}`}
|
}`}
|
||||||
>
|
>
|
||||||
{e}
|
{e}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -93,15 +104,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
|
|
||||||
useEffect(() => { fetchItems(); }, [campaign.id]);
|
useEffect(() => { fetchItems(); }, [campaign.id]);
|
||||||
|
|
||||||
// Listen for emoji-select from ResourceBrowser EmojisTab
|
|
||||||
useEffect(() => {
|
|
||||||
const handler = (e: Event) => {
|
|
||||||
const detail = (e as CustomEvent).detail;
|
|
||||||
if (detail?.emoji) setEditEmoji(detail.emoji);
|
|
||||||
};
|
|
||||||
window.addEventListener("emoji-select", handler);
|
|
||||||
return () => window.removeEventListener("emoji-select", handler);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const updateItem = async (item: Item) => {
|
const updateItem = async (item: Item) => {
|
||||||
await fetch(`/api/campaigns/${campaign.id}/items`, {
|
await fetch(`/api/campaigns/${campaign.id}/items`, {
|
||||||
@@ -200,10 +203,6 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
setUploading(false);
|
setUploading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const playSoundOnce = (url: string) => {
|
|
||||||
try { const a = new Audio(url); a.preload = "auto"; a.volume = 0.4; a.play().catch(() => {}); } catch {}
|
|
||||||
};
|
|
||||||
|
|
||||||
// ─── Drag & Drop handlers ───────────────────────────────────────
|
// ─── Drag & Drop handlers ───────────────────────────────────────
|
||||||
|
|
||||||
const handleDragOver = useCallback((e: React.DragEvent, idx: number) => {
|
const handleDragOver = useCallback((e: React.DragEvent, idx: number) => {
|
||||||
@@ -225,7 +224,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
if (!item) return;
|
if (!item) return;
|
||||||
|
|
||||||
if (data.type === "sound") {
|
if (data.type === "sound") {
|
||||||
playSoundOnce(data.url);
|
playSoundOnce(data.url, data.originalName);
|
||||||
await updateItem({ ...item, soundCategory: "custom", soundUrl: data.url });
|
await updateItem({ ...item, soundCategory: "custom", soundUrl: data.url });
|
||||||
} else if (data.type === "image") {
|
} else if (data.type === "image") {
|
||||||
await updateItem({ ...item, imageUrl: data.url });
|
await updateItem({ ...item, imageUrl: data.url });
|
||||||
@@ -261,20 +260,22 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex-1 min-w-[150px]">
|
||||||
|
<label className="text-[9px] font-mono text-slate-600 uppercase">Text</label>
|
||||||
|
<Input
|
||||||
|
placeholder="Reactor explodes"
|
||||||
|
value={editText}
|
||||||
|
onChange={e => setEditText(e.target.value)}
|
||||||
|
className="font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-[9px] font-mono text-slate-600 uppercase">Emoji — click to select</label>
|
||||||
|
<EmojiPickerGrid value={editEmoji} onChange={setEditEmoji} />
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-2 items-end">
|
<div className="flex flex-wrap gap-2 items-end">
|
||||||
<div className="flex-1 min-w-[150px]">
|
|
||||||
<label className="text-[9px] font-mono text-slate-600 uppercase">Text</label>
|
|
||||||
<Input
|
|
||||||
placeholder="Reactor explodes"
|
|
||||||
value={editText}
|
|
||||||
onChange={e => setEditText(e.target.value)}
|
|
||||||
className="font-mono text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="text-[9px] font-mono text-slate-600 uppercase">Emoji</label>
|
|
||||||
<EmojiPicker value={editEmoji} onChange={setEditEmoji} />
|
|
||||||
</div>
|
|
||||||
<div className="w-32">
|
<div className="w-32">
|
||||||
<label className="text-[9px] font-mono text-slate-600 uppercase">Sound</label>
|
<label className="text-[9px] font-mono text-slate-600 uppercase">Sound</label>
|
||||||
<Select
|
<Select
|
||||||
@@ -304,7 +305,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
<input
|
<input
|
||||||
ref={fileInputRef}
|
ref={fileInputRef}
|
||||||
type="file"
|
type="file"
|
||||||
accept=".ogg"
|
accept="audio/*,video/*"
|
||||||
className="hidden"
|
className="hidden"
|
||||||
onChange={e => { const f = e.target.files?.[0]; if (f) uploadSound(f); }}
|
onChange={e => { const f = e.target.files?.[0]; if (f) uploadSound(f); }}
|
||||||
/>
|
/>
|
||||||
@@ -320,7 +321,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
{editSoundUrl && (
|
{editSoundUrl && (
|
||||||
<div className="flex items-center gap-1 text-[10px] font-mono text-cyan-400">
|
<div className="flex items-center gap-1 text-[10px] font-mono text-cyan-400">
|
||||||
<span>✓ sound loaded</span>
|
<span>✓ sound loaded</span>
|
||||||
<button type="button" onClick={() => playSoundOnce(editSoundUrl)} className="px-1.5 py-0.5 rounded bg-slate-700/50 hover:bg-slate-600/50 text-xs cursor-pointer">▶</button>
|
<button type="button" onClick={() => playSoundOnce(editSoundUrl!, "Preview")} className="px-1.5 py-0.5 rounded bg-slate-700/50 hover:bg-slate-600/50 text-xs cursor-pointer">▶</button>
|
||||||
<button type="button" onClick={() => setEditSoundUrl(null)} className="px-1.5 py-0.5 rounded bg-slate-700/50 hover:bg-red-800/50 text-xs cursor-pointer">✕</button>
|
<button type="button" onClick={() => setEditSoundUrl(null)} className="px-1.5 py-0.5 rounded bg-slate-700/50 hover:bg-red-800/50 text-xs cursor-pointer">✕</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -377,7 +378,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
{item.soundUrl && (
|
{item.soundUrl && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={e => { e.stopPropagation(); playSoundOnce(item.soundUrl!); }}
|
onClick={e => { e.stopPropagation(); playSoundOnce(item.soundUrl!, item.text); }}
|
||||||
className="text-[10px] text-cyan-500/60 hover:text-cyan-300 cursor-pointer relative z-10"
|
className="text-[10px] text-cyan-500/60 hover:text-cyan-300 cursor-pointer relative z-10"
|
||||||
>
|
>
|
||||||
🔊
|
🔊
|
||||||
@@ -399,6 +400,9 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
|
|||||||
{/* Resource Browser dock */}
|
{/* Resource Browser dock */}
|
||||||
<ResourceBrowser visible={showBrowser} onClose={() => setShowBrowser(false)} />
|
<ResourceBrowser visible={showBrowser} onClose={() => setShowBrowser(false)} />
|
||||||
|
|
||||||
|
{/* Sound playback bar */}
|
||||||
|
<SoundPlayerBar />
|
||||||
|
|
||||||
{/* All Items list */}
|
{/* All Items list */}
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<h4 className="text-[10px] font-mono text-slate-600 uppercase">All Items</h4>
|
<h4 className="text-[10px] font-mono text-slate-600 uppercase">All Items</h4>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback, useRef } from "react";
|
import { useState, useEffect, useCallback, useRef } from "react";
|
||||||
import { useDropzone } from "react-dropzone";
|
import { useDropzone } from "react-dropzone";
|
||||||
import { Howl } from "howler";
|
import { playSoundOnce } from "@/lib/sounds";
|
||||||
|
|
||||||
// ─── Types ──────────────────────────────────────────────────────────
|
// ─── Types ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -33,71 +33,7 @@ export type DragData =
|
|||||||
| { type: "image"; url: string; originalName: string }
|
| { type: "image"; url: string; originalName: string }
|
||||||
| { type: "emoji"; emoji: string };
|
| { type: "emoji"; emoji: string };
|
||||||
|
|
||||||
// ─── Howl helper ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const howlCache = new Map<string, Howl>();
|
|
||||||
|
|
||||||
function playPreview(url: string) {
|
|
||||||
let h = howlCache.get(url);
|
|
||||||
if (!h) {
|
|
||||||
h = new Howl({ src: [url], format: ["mp3", "ogg"], volume: 0.4, preload: true });
|
|
||||||
howlCache.set(url, h);
|
|
||||||
}
|
|
||||||
h.play();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Emoji Picker (inline, searchable) ──────────────────────────────
|
|
||||||
|
|
||||||
const EMOJI_LIST = [
|
|
||||||
"😀", "😂", "🤣", "😍", "🥰", "😘", "😊", "😎", "🤩", "🥳", "🤯", "😱",
|
|
||||||
"😈", "🤡", "💀", "👻", "👽", "🤖", "🎃", "😺", "🙈", "🙉", "🙊", "💩",
|
|
||||||
"🔥", "🌊", "💥", "💫", "⭐", "🌟", "✨", "⚡", "☄️", "💧", "🧊", "🌋",
|
|
||||||
"🎉", "🎊", "🎈", "🎁", "🏆", "🥇", "💎", "🔮", "🪄", "🧨", "🔫", "⚔️",
|
|
||||||
"🛡️", "🚀", "🛸", "🚁", "⚓", "🌀", "🌈", "🌪️", "☢️", "☣️", "⚕️", "🧬",
|
|
||||||
"💉", "💊", "🩸", "🧪", "🔬", "🔭", "📡", "🎯", "🎲", "♟️", "🧩", "🎭",
|
|
||||||
"🎵", "🎶", "🎺", "📯", "🔔", "🎤", "🎧", "📢", "📣", "🔊", "🔇", "💤",
|
|
||||||
"💣", "🔪", "🪦", "⚰️", "🪤", "🧲", "🗝️", "🔑", "🔓", "🔒", "🛠️", "⛓️",
|
|
||||||
"🧹", "🪠", "🔧", "⚙️", "📦", "📀", "💿", "📹", "📸", "📷", "🖼️", "🎨",
|
|
||||||
"🍺", "🍻", "🍷", "🥃", "🍸", "🍹", "🧉", "🍕", "🍔", "🌭", "🍿", "🧀",
|
|
||||||
"🥜", "🌶️", "🍄", "🥚", "🧅", "🥕", "🥦", "🫁", "🧠", "👀", "👁️", "🫀",
|
|
||||||
"💋", "🫂", "🤝", "👍", "👎", "👊", "✊", "🤛", "🤜", "👆", "👇", "🖕",
|
|
||||||
"💪", "🦵", "🦶", "👂", "👃", "🧑🚀", "🧑🔧", "🧑⚕️", "🧑✈️", "🧑🏫", "🧑🎤", "🧑🍳",
|
|
||||||
"🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨", "🐯", "🦁", "🐮",
|
|
||||||
"🦈", "🐙", "🦑", "🐋", "🐬", "🦭", "🐊", "🦎", "🐍", "🐢", "🦖", "🦕",
|
|
||||||
"🦟", "🦗", "🐛", "🪱", "🦋", "🐌", "🐞", "🐜", "🦂", "🕷️", "🦀", "🪸",
|
|
||||||
];
|
|
||||||
|
|
||||||
function EmojiPickerGrid({ onSelect }: { onSelect: (emoji: string) => void }) {
|
|
||||||
const [search, setSearch] = useState("");
|
|
||||||
const filtered = search ? EMOJI_LIST.filter(e => e.includes(search)) : EMOJI_LIST;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
placeholder="Search emoji..."
|
|
||||||
value={search}
|
|
||||||
onChange={e => setSearch(e.target.value)}
|
|
||||||
className="w-full bg-slate-800/60 border border-slate-700/30 rounded px-2 py-1.5 text-xs font-mono text-slate-200 placeholder:text-slate-600 outline-none focus:border-cyan-500/50"
|
|
||||||
/>
|
|
||||||
<div className="grid grid-cols-10 gap-1 max-h-48 overflow-y-auto">
|
|
||||||
{filtered.map(e => (
|
|
||||||
<button
|
|
||||||
key={e}
|
|
||||||
draggable
|
|
||||||
onDragStart={ev => {
|
|
||||||
ev.dataTransfer.setData("application/json", JSON.stringify({ type: "emoji", emoji: e } satisfies DragData));
|
|
||||||
}}
|
|
||||||
onClick={() => onSelect(e)}
|
|
||||||
className="w-8 h-8 flex items-center justify-center text-base rounded hover:bg-slate-700/60 cursor-pointer active:scale-90 transition-transform"
|
|
||||||
>
|
|
||||||
{e}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Sounds Tab ─────────────────────────────────────────────────────
|
// ─── Sounds Tab ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -143,7 +79,7 @@ function SoundsTab() {
|
|||||||
} catch {}
|
} catch {}
|
||||||
setUploading(false);
|
setUploading(false);
|
||||||
},
|
},
|
||||||
accept: { "audio/ogg": [".ogg"] },
|
accept: { "audio/*": [".mp3", ".ogg", ".wav", ".flac", ".aac", ".m4a", ".wma", ".opus", ".webm"], "video/*": [".mp4", ".avi", ".mov", ".mkv", ".webm", ".wmv", ".flv"] },
|
||||||
multiple: true,
|
multiple: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -197,7 +133,7 @@ function SoundsTab() {
|
|||||||
|
|
||||||
<div {...getRootProps()} className="border-2 border-dashed border-slate-700/40 rounded-lg p-3 text-center cursor-pointer hover:border-cyan-600/40 transition-colors">
|
<div {...getRootProps()} className="border-2 border-dashed border-slate-700/40 rounded-lg p-3 text-center cursor-pointer hover:border-cyan-600/40 transition-colors">
|
||||||
<input {...getInputProps()} />
|
<input {...getInputProps()} />
|
||||||
<p className="text-[10px] font-mono text-slate-500">Drop OGG files here or click to upload</p>
|
<p className="text-[10px] font-mono text-slate-500">Drop audio/video files here or click to upload</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Library */}
|
{/* Library */}
|
||||||
@@ -211,7 +147,7 @@ function SoundsTab() {
|
|||||||
label={s.originalName}
|
label={s.originalName}
|
||||||
duration={s.duration}
|
duration={s.duration}
|
||||||
url={s.url}
|
url={s.url}
|
||||||
onPlay={() => playPreview(s.url)}
|
onPlay={() => playSoundOnce(s.url, s.originalName)}
|
||||||
onDelete={() => deleteSound(filename)}
|
onDelete={() => deleteSound(filename)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -244,7 +180,7 @@ function SoundsTab() {
|
|||||||
key={r.id}
|
key={r.id}
|
||||||
name={r.name}
|
name={r.name}
|
||||||
duration={r.duration}
|
duration={r.duration}
|
||||||
onPreview={() => r.previewUrl && playPreview(r.previewUrl)}
|
onPreview={() => r.previewUrl && playSoundOnce(r.previewUrl, r.name)}
|
||||||
onImport={() => importSound(r)}
|
onImport={() => importSound(r)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -389,7 +325,7 @@ function FreesoundRow({ name, duration, onPreview, onImport }: {
|
|||||||
|
|
||||||
// ─── Main ResourceBrowser ───────────────────────────────────────────
|
// ─── Main ResourceBrowser ───────────────────────────────────────────
|
||||||
|
|
||||||
type Tab = "sounds" | "images" | "emojis";
|
type Tab = "sounds" | "images";
|
||||||
|
|
||||||
export function ResourceBrowser({ visible, onClose }: { visible: boolean; onClose: () => void }) {
|
export function ResourceBrowser({ visible, onClose }: { visible: boolean; onClose: () => void }) {
|
||||||
const [tab, setTab] = useState<Tab>("sounds");
|
const [tab, setTab] = useState<Tab>("sounds");
|
||||||
@@ -403,7 +339,6 @@ export function ResourceBrowser({ visible, onClose }: { visible: boolean; onClos
|
|||||||
{([
|
{([
|
||||||
{ key: "sounds" as const, label: "🔊 Sounds" },
|
{ key: "sounds" as const, label: "🔊 Sounds" },
|
||||||
{ key: "images" as const, label: "🖼️ Images" },
|
{ key: "images" as const, label: "🖼️ Images" },
|
||||||
{ key: "emojis" as const, label: "😀 Emojis" },
|
|
||||||
]).map(t => (
|
]).map(t => (
|
||||||
<button
|
<button
|
||||||
key={t.key}
|
key={t.key}
|
||||||
@@ -427,17 +362,9 @@ export function ResourceBrowser({ visible, onClose }: { visible: boolean; onClos
|
|||||||
<div className="max-h-72 overflow-y-auto">
|
<div className="max-h-72 overflow-y-auto">
|
||||||
{tab === "sounds" && <SoundsTab />}
|
{tab === "sounds" && <SoundsTab />}
|
||||||
{tab === "images" && <ImagesTab />}
|
{tab === "images" && <ImagesTab />}
|
||||||
{tab === "emojis" && <EmojisTab />}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function EmojisTab() {
|
|
||||||
const handleSelect = (emoji: string) => {
|
|
||||||
// Dispatch a custom event so ItemEditor can pick it up
|
|
||||||
window.dispatchEvent(new CustomEvent("emoji-select", { detail: { emoji } }));
|
|
||||||
};
|
|
||||||
|
|
||||||
return <div className="p-3"><EmojiPickerGrid onSelect={handleSelect} /></div>;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { subscribe, getPlaybackState, stopCurrent, PlaybackState } from "@/lib/player";
|
||||||
|
|
||||||
|
export function SoundPlayerBar() {
|
||||||
|
const [s, setS] = useState<PlaybackState>(getPlaybackState());
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const unsub = subscribe(setS);
|
||||||
|
return unsub;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!s.isPlaying) return null;
|
||||||
|
|
||||||
|
const pct = Math.min((s.elapsed / s.duration) * 100, 100);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border-t border-slate-700/30 bg-slate-950/95 px-3 py-2">
|
||||||
|
<div className="flex items-center gap-2 text-[10px] font-mono max-w-2xl mx-auto">
|
||||||
|
<span className="text-cyan-400 shrink-0">🔊</span>
|
||||||
|
<span className="text-slate-300 truncate max-w-[200px]">{s.name}</span>
|
||||||
|
<div className="flex-1 h-1.5 bg-slate-800 rounded-full overflow-hidden min-w-[80px]">
|
||||||
|
<div
|
||||||
|
className="h-full bg-cyan-500 transition-all duration-100 rounded-full"
|
||||||
|
style={{ width: `${pct}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="text-slate-500 shrink-0 w-16 text-right tabular-nums">
|
||||||
|
{s.elapsed.toFixed(1)}s / {s.duration.toFixed(0)}s
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={stopCurrent}
|
||||||
|
className="px-2 py-0.5 rounded bg-slate-800 hover:bg-red-800/60 text-slate-400 hover:text-red-300 cursor-pointer shrink-0"
|
||||||
|
>
|
||||||
|
■
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+1
-1
@@ -7,7 +7,7 @@ services:
|
|||||||
- "80:3000"
|
- "80:3000"
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
- ./uploads:/app/public/uploads
|
- ./uploads:/app/data/uploads
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=production
|
- NODE_ENV=production
|
||||||
- FREESOUND_API_KEY=${FREESOUND_API_KEY}
|
- FREESOUND_API_KEY=${FREESOUND_API_KEY}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { execSync } from "child_process";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert any audio/video file to a 6-second compressed MP3 via ffmpeg.
|
||||||
|
* Returns true on success, false on failure.
|
||||||
|
* The output file is always mp3Path (overwritten if exists).
|
||||||
|
*/
|
||||||
|
export function convertToCompressedMp3(inputPath: string, mp3Path: string): boolean {
|
||||||
|
try {
|
||||||
|
execSync(
|
||||||
|
`ffmpeg -i "${inputPath}" -t 6 -vn -codec:a libmp3lame -b:a 64k -y "${mp3Path}" 2>/dev/null`,
|
||||||
|
{ timeout: 30000 }
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
import { Howl } from "howler";
|
||||||
|
|
||||||
|
export type PlaybackState = {
|
||||||
|
isPlaying: boolean;
|
||||||
|
url: string | null;
|
||||||
|
name: string | null;
|
||||||
|
elapsed: number;
|
||||||
|
duration: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Listener = (s: PlaybackState) => void;
|
||||||
|
|
||||||
|
const MAX_SECONDS = 6;
|
||||||
|
const FADE_MS = 500;
|
||||||
|
|
||||||
|
let state: PlaybackState = {
|
||||||
|
isPlaying: false,
|
||||||
|
url: null,
|
||||||
|
name: null,
|
||||||
|
elapsed: 0,
|
||||||
|
duration: MAX_SECONDS,
|
||||||
|
};
|
||||||
|
|
||||||
|
const listeners = new Set<Listener>();
|
||||||
|
|
||||||
|
let howlInstance: Howl | null = null;
|
||||||
|
let soundId: number | null = null;
|
||||||
|
let stopTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let progressTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
function emit() {
|
||||||
|
listeners.forEach(fn => fn(state));
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetTimers() {
|
||||||
|
if (stopTimer) clearTimeout(stopTimer);
|
||||||
|
if (progressTimer) clearInterval(progressTimer);
|
||||||
|
stopTimer = null;
|
||||||
|
progressTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopSound() {
|
||||||
|
if (howlInstance && soundId !== null) {
|
||||||
|
howlInstance.stop(soundId);
|
||||||
|
}
|
||||||
|
howlInstance = null;
|
||||||
|
soundId = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPlaybackState(): PlaybackState {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribe(fn: Listener): () => void {
|
||||||
|
listeners.add(fn);
|
||||||
|
return () => listeners.delete(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function playUrl(url: string, name?: string) {
|
||||||
|
stopCurrent();
|
||||||
|
|
||||||
|
const displayName = name || url.split("/").pop() || url;
|
||||||
|
|
||||||
|
howlInstance = new Howl({
|
||||||
|
src: [url],
|
||||||
|
format: url.endsWith(".mp3") ? ["mp3"] : url.endsWith(".ogg") ? ["ogg"] : ["mp3", "ogg"],
|
||||||
|
volume: 0.4,
|
||||||
|
});
|
||||||
|
|
||||||
|
soundId = howlInstance.play();
|
||||||
|
|
||||||
|
state = { isPlaying: true, url, name: displayName, elapsed: 0, duration: MAX_SECONDS };
|
||||||
|
emit();
|
||||||
|
|
||||||
|
// Progress tick
|
||||||
|
progressTimer = setInterval(() => {
|
||||||
|
if (howlInstance && soundId !== null) {
|
||||||
|
const seek = howlInstance.seek(soundId) as number;
|
||||||
|
state = { ...state, elapsed: seek };
|
||||||
|
emit();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
// Cap at MAX_SECONDS with fadeout
|
||||||
|
const fadeStart = (MAX_SECONDS - FADE_MS / 1000) * 1000;
|
||||||
|
stopTimer = setTimeout(() => {
|
||||||
|
if (howlInstance && soundId !== null) {
|
||||||
|
try { howlInstance.fade(0.4, 0, FADE_MS, soundId); } catch {}
|
||||||
|
setTimeout(() => stopCurrent(), FADE_MS);
|
||||||
|
}
|
||||||
|
}, fadeStart);
|
||||||
|
|
||||||
|
// Natural end
|
||||||
|
howlInstance.on("end", () => stopCurrent());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stopCurrent() {
|
||||||
|
stopSound();
|
||||||
|
resetTimers();
|
||||||
|
state = { isPlaying: false, url: null, name: null, elapsed: 0, duration: MAX_SECONDS };
|
||||||
|
emit();
|
||||||
|
}
|
||||||
+22
-7
@@ -1,3 +1,5 @@
|
|||||||
|
import { playUrl, stopCurrent } from "@/lib/player";
|
||||||
|
|
||||||
let audioCtx: AudioContext | null = null;
|
let audioCtx: AudioContext | null = null;
|
||||||
|
|
||||||
function getCtx(): AudioContext {
|
function getCtx(): AudioContext {
|
||||||
@@ -107,15 +109,28 @@ export function playChaosRiser() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function playSoundUrl(url: string) {
|
// ─── URL playback via shared player ──────────────────────────────
|
||||||
try {
|
|
||||||
const audio = new Audio(url);
|
/**
|
||||||
audio.preload = "auto";
|
* Play a sound file URL (MP3/OGG). Goes through the shared player,
|
||||||
audio.volume = 0.4;
|
* which caps at 6s with fadeout and shows playback UI.
|
||||||
audio.play().catch(() => {});
|
*/
|
||||||
} catch {}
|
export function playSoundUrl(url: string, name?: string) {
|
||||||
|
playUrl(url, name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-shot play with a display name. Same underlying player.
|
||||||
|
*/
|
||||||
|
export function playSoundOnce(url: string, name?: string) {
|
||||||
|
playUrl(url, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop current playback immediately.
|
||||||
|
*/
|
||||||
|
export { stopCurrent, getPlaybackState, subscribe } from "@/lib/player";
|
||||||
|
|
||||||
export function playSound(category: string, soundUrl?: string | null) {
|
export function playSound(category: string, soundUrl?: string | null) {
|
||||||
if (soundUrl) {
|
if (soundUrl) {
|
||||||
playSoundUrl(soundUrl);
|
playSoundUrl(soundUrl);
|
||||||
|
|||||||
Reference in New Issue
Block a user