This repository was archived by the owner on Sep 27, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
208 lines (186 loc) · 6.02 KB
/
Copy pathserver.js
File metadata and controls
208 lines (186 loc) · 6.02 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { HTTPServer } from "./dist/server/http-server.js";
import { MusicServer } from "./dist/server/music-server.js";
import { generateUniqueId } from "./dist/util/unique-id.js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
// Configuration
const PORT = 3001;
const WAV_FILE = path.join(
path.dirname(fileURLToPath(import.meta.url)),
"example-assets/server/sample.wav",
);
const ART_FILE = path.join(
path.dirname(fileURLToPath(import.meta.url)),
"example-assets/server/927-square.png",
);
const REPLAY_INTERVAL = 10000; // Replay WAV file every 5 seconds
const logger = {
log: (...args) =>
args[0] ? console.log(new Date().toISOString(), ...args) : console.log(""),
error: (...args) =>
console.error(new Date().toISOString(), "ERROR:", ...args),
};
/**
* Parse a WAV file and extract audio data and format information
* This is a simplified parser that works with standard PCM WAV files
*/
function parseWavFile(filePath) {
// Read file synchronously
const buffer = fs.readFileSync(filePath);
// Verify WAV header
const header = buffer.toString("utf8", 0, 4);
if (header !== "RIFF") {
throw new Error("Not a valid WAV file");
}
// Basic WAV header parsing
const sampleRate = buffer.readUInt32LE(24);
const numChannels = buffer.readUInt16LE(22);
const bitsPerSample = buffer.readUInt16LE(34);
logger.log(
`WAV file info: ${sampleRate}Hz, ${numChannels} channels, ${bitsPerSample} bits`,
);
// Find data chunk (simplistic approach - real WAV files might have different chunks)
let dataOffset = 44; // Default for standard WAV files
let dataSize = buffer.readUInt32LE(40);
// Extract audio data as Int16Array (assuming PCM format)
const audioData = new Int16Array(dataSize / 2);
for (let i = 0; i < audioData.length; i++) {
audioData[i] = buffer.readInt16LE(dataOffset + i * 2);
}
return {
sampleRate,
channels: numChannels,
bitDepth: bitsPerSample,
audioData,
};
}
async function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Main function to start the server and handle audio streaming
*/
async function main() {
try {
logger.log(`Reading WAV file: ${WAV_FILE}`);
const wavData = parseWavFile(WAV_FILE);
const artData = fs.readFileSync(ART_FILE);
// Create and start the Source server
const musicServer = new MusicServer(
{
source_id: generateUniqueId("server"),
name: "SDKSample",
},
logger,
);
const httpServer = new HTTPServer(musicServer, PORT, logger);
try {
httpServer.start();
} catch (error) {
logger.error("Failed to start server", error);
process.exit(1);
}
// Example server maintains a single group that all clients join
const group = musicServer.createGroup();
musicServer.on("client-added", (client) => {
group.addClient(client);
});
// Start audio session and stream periodically
const playAudio = async () => {
logger.log("");
logger.log("Sending WAV audio data to connected clients");
let endRequested = false;
const session = group.startSession(
"pcm",
wavData.sampleRate,
wavData.channels,
wavData.bitDepth,
);
session.on("stream-command", (command) => {
if (command.command === "stop") {
endRequested = true;
logger.log("Stop command received, stopping audio playback.");
}
});
session.on("player-state", (state) => {
logger.log("Player state updated:", state);
});
session.sendMetadata({
title: "Sample Audio",
artist: "Someone on the internet",
album: null,
year: null,
track: null,
group_members: [],
support_commands: ["play", "stop"],
repeat: "off",
shuffle: false,
});
session.sendMediaArt("image/png", artData);
let start = performance.timeOrigin + performance.now() + 500;
const timeSlice = 50; // ms
const bytesPerSlice =
(timeSlice / 1000) * wavData.sampleRate * wavData.channels;
for (let i = 0; i < wavData.audioData.length; i += bytesPerSlice) {
if (endRequested) {
break;
}
// Mimick metadata update
if (i % (bytesPerSlice * 10) === 0) {
session.sendMetadata({
title: `Sample Audio ${i}`,
artist: "Someone on the internet",
album: null,
year: null,
track: null,
group_members: [],
support_commands: ["play", "stop"],
repeat: "off",
shuffle: false,
});
}
const chunk = wavData.audioData.slice(i, i + bytesPerSlice);
// Only do actual audio sending if there are clients connected
if (group.size > 0) {
session.sendPCMAudioChunk(
chunk,
// We send microsecond timestamp as integer
Math.round(start * 1000),
);
}
// Usually equal to timeSlice, but shorter for last chunk
start += (chunk.length / bytesPerSlice) * timeSlice;
// Send the audio if it should start playing within 1000 ms
const sleepDuration =
start - performance.timeOrigin - performance.now() - 1000;
if (sleepDuration > 0) {
await sleep(sleepDuration);
}
}
// end session after audio is done playing.
await sleep(
start -
Date.now() +
// some extra time to make sure all clients have received the audio
100,
);
session.end();
await sleep(REPLAY_INTERVAL);
playAudio();
};
// Then play periodically so new clients will eventually hear the audio
setTimeout(playAudio, REPLAY_INTERVAL);
// Handle process termination
process.on("SIGINT", () => {
logger.log("Shutting down server...");
httpServer.stop();
process.exit(0);
});
} catch (error) {
logger.error("Server error:", error);
process.exit(1);
}
}
// Run the main function
main();