|
| 1 | +export function getFromFlacBuffer(buffer: ArrayBuffer): Record<string, string> { |
| 2 | + const dataView = new DataView(buffer); |
| 3 | + |
| 4 | + // Verify the FLAC signature |
| 5 | + const signature = String.fromCharCode(...new Uint8Array(buffer, 0, 4)); |
| 6 | + if (signature !== "fLaC") { |
| 7 | + console.error("Not a valid FLAC file"); |
| 8 | + return; |
| 9 | + } |
| 10 | + |
| 11 | + // Parse metadata blocks |
| 12 | + let offset = 4; |
| 13 | + let vorbisComment = null; |
| 14 | + while (offset < dataView.byteLength) { |
| 15 | + const isLastBlock = dataView.getUint8(offset) & 0x80; |
| 16 | + const blockType = dataView.getUint8(offset) & 0x7f; |
| 17 | + const blockSize = dataView.getUint32(offset, false) & 0xffffff; |
| 18 | + offset += 4; |
| 19 | + |
| 20 | + if (blockType === 4) { |
| 21 | + // Vorbis Comment block type |
| 22 | + vorbisComment = parseVorbisComment( |
| 23 | + new DataView(buffer, offset, blockSize) |
| 24 | + ); |
| 25 | + } |
| 26 | + |
| 27 | + offset += blockSize; |
| 28 | + if (isLastBlock) break; |
| 29 | + } |
| 30 | + |
| 31 | + return vorbisComment; |
| 32 | +} |
| 33 | + |
| 34 | +export function getFromFlacFile(file: File): Promise<Record<string, string>> { |
| 35 | + return new Promise((r) => { |
| 36 | + const reader = new FileReader(); |
| 37 | + reader.onload = function (event) { |
| 38 | + const arrayBuffer = event.target.result as ArrayBuffer; |
| 39 | + r(getFromFlacBuffer(arrayBuffer)); |
| 40 | + }; |
| 41 | + reader.readAsArrayBuffer(file); |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +// Function to parse the Vorbis Comment block |
| 46 | +function parseVorbisComment(dataView: DataView): Record<string, string> { |
| 47 | + let offset = 0; |
| 48 | + const vendorLength = dataView.getUint32(offset, true); |
| 49 | + offset += 4; |
| 50 | + const vendorString = getString(dataView, offset, vendorLength); |
| 51 | + offset += vendorLength; |
| 52 | + |
| 53 | + const userCommentListLength = dataView.getUint32(offset, true); |
| 54 | + offset += 4; |
| 55 | + const comments = {}; |
| 56 | + for (let i = 0; i < userCommentListLength; i++) { |
| 57 | + const commentLength = dataView.getUint32(offset, true); |
| 58 | + offset += 4; |
| 59 | + const comment = getString(dataView, offset, commentLength); |
| 60 | + offset += commentLength; |
| 61 | + |
| 62 | + const [key, value] = comment.split("="); |
| 63 | + |
| 64 | + comments[key] = value; |
| 65 | + } |
| 66 | + |
| 67 | + return comments; |
| 68 | +} |
| 69 | + |
| 70 | +function getString(dataView: DataView, offset: number, length: number): string { |
| 71 | + let string = ""; |
| 72 | + for (let i = 0; i < length; i++) { |
| 73 | + string += String.fromCharCode(dataView.getUint8(offset + i)); |
| 74 | + } |
| 75 | + return string; |
| 76 | +} |
0 commit comments