📄
src/lib/birdnet.svelte.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import BirdNetWorker from "./birdnet.worker.ts?worker";
import type { Prediction, WorkerInMessage, WorkerOutMessage } from "./types";
import { addDetection } from "./history";
import { gps } from "./gps.svelte";
class BirdNetService {
workerReady = $state(false);
predictions = $state<Prediction[]>([]);
readonly #worker: Worker;
constructor() {
this.#worker = new BirdNetWorker();
this.#worker.addEventListener(
"message",
(e: MessageEvent<WorkerOutMessage>) => {
const msg = e.data;
if (msg.type === "ready") {
this.workerReady = true;
} else if (msg.type === "results") {
this.predictions = msg.predictions;
for (const p of msg.predictions) addDetection(p, gps.coords);
}
},
);
this.#worker.postMessage({ type: "init" } satisfies WorkerInMessage);
}
analyze(samples: Float32Array): void {
this.#worker.postMessage(
{ type: "analyze", samples } satisfies WorkerInMessage,
[samples.buffer],
);
}
clearPredictions(): void {
this.predictions = [];
}
}
export const birdnet = new BirdNetService();