zaibihassan commited on
Commit
df7f952
·
verified ·
1 Parent(s): 74a3447

Upload IMPLEMENTATION.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. IMPLEMENTATION.md +303 -159
IMPLEMENTATION.md CHANGED
@@ -1,123 +1,213 @@
1
  # Implementation Guide
2
 
3
- This guide explains how the audio files and word-by-word timestamp data are structured in this repository, and provides implementation examples to help you build a seamless playback and highlighting experience across various major technology stacks.
4
 
5
- ## 🗂Data Structure
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- The repository uses a highly structured directory format to make programmatic access to any verse's audio and timing data incredibly simple.
 
 
8
 
9
- ### Directory Layout
10
- Files are organized in the following hierarchy:
11
- `/{reciter_name}/{surah_index}/{surah_index}{verse_index}.[opus|json]`
 
12
 
13
  Where:
14
- - `{reciter_name}`: The slugged directory name of the reciter (e.g., `abdul-basit-abdul-samad-murattal-hafs-950`).
15
- - `{surah_index}`: The Surah number, strictly 3-digit zero-padded (e.g., `001` for Al-Fatihah, `114` for An-Nas).
16
- - `{verse_index}`: The Verse number, strictly 3-digit zero-padded. Combined, `{surah_index}{verse_index}` creates a 6-digit filename prefix (e.g., `001001` or `114006`).
17
-
18
- **Example Paths**:
19
- - 🎵 **Audio**: `https://cdn.jsdelivr.net/gh/zaibihsn/recitation-all@main/abdul-basit-abdul-samad-murattal-hafs-950/001/001001.opus`
20
- - ⏱️ **Metadata**: `https://cdn.jsdelivr.net/gh/zaibihsn/recitation-all@main/abdul-basit-abdul-samad-murattal-hafs-950/001/001001.json`
21
-
22
- ### JSON Metadata Formats
23
- When fetching the `.json` files, you will encounter one of two primary formats depending on the data source. Your parsing logic should seamlessly handle both.
24
-
25
- **Format A (Flat Array)**
26
- A direct array of timestamps. Each inner array element represents a specific word.
27
- ```json
28
- [
29
- [0, 1, 0, 920],
30
- [1, 2, 1080, 1440],
31
- [2, 3, 2120, 2440]
32
- ]
33
  ```
34
- *Structure: `[current_word_index, next_word_index, start_time_ms, end_time_ms]`*
35
-
36
- **Format B (Detailed Object)**
37
- An object containing verse metadata along with an array of word segments.
38
- ```json
39
- {
40
- "verse_key": "1:1",
41
- "timestamp_from": 0,
42
- "timestamp_to": 8037,
43
- "segments": [
44
- [1, 0, 579],
45
- [2, 579, 1331]
46
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  }
48
  ```
49
- *Structure within `segments`: `[word_index, start_time_ms, end_time_ms]`*
 
 
 
 
 
50
 
51
  ---
52
 
53
  ## 💻 Tech Stack Implementations
54
 
55
- The core concept across all frameworks is:
56
- 1. Fetch the JSON timestamp array for a verse.
57
- 2. Load the Audio track for that verse.
58
- 3. Listen to the audio stream's current position (time).
59
- 4. Given the current time in milliseconds, loop over the timestamps and find the word where `start_time <= current_time <= end_time`.
60
- 5. Apply a "highlighted" style/class to that word index.
 
 
 
61
 
62
- ### 1. Vanilla JavaScript
63
  ```javascript
64
- const audio = new Audio("https://cdn.jsdelivr.net/gh/zaibihsn/recitation-all@main/abdul-basit.../001/001001.opus");
65
- let timestamps = []; // E.g., [[0,1,0,920], [1,2,1080,1440]]
66
- let activeWordIndex = -1;
67
 
68
- audio.addEventListener("timeupdate", () => {
69
- const currentTimeMs = audio.currentTime * 1000;
70
-
71
- // Find matching word
72
- const match = timestamps.find(t => {
73
- // Handle both format variants appropriately (Format A in this example)
74
- return currentTimeMs >= t[2] && currentTimeMs <= t[3];
75
- });
76
 
77
- if (match) {
78
- const newWordIndex = match[0];
79
- if (activeWordIndex !== newWordIndex) {
80
- activeWordIndex = newWordIndex;
81
- highlightWordInDOM(activeWordIndex); // Your custom function
82
- }
83
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  });
85
 
 
 
 
 
 
 
 
 
 
 
86
  audio.play();
87
  ```
88
 
89
  ### 2. React.js
 
90
  ```tsx
91
  import React, { useState, useEffect, useRef } from 'react';
92
 
93
- const QuranPlayer = ({ audioUrl, timestamps, words }) => {
94
- const audioRef = useRef(null);
 
 
95
  const [activeWordIndex, setActiveWordIndex] = useState(-1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  const handleTimeUpdate = () => {
98
- if (!audioRef.current || !timestamps) return;
99
-
100
  const currentTimeMs = audioRef.current.currentTime * 1000;
101
-
102
- // Assume Format A timestamps: [wordIdx, nextIdx, startMs, endMs]
103
- const match = timestamps.find(
104
- (t) => currentTimeMs >= t[2] && currentTimeMs <= t[3]
 
105
  );
106
 
107
- if (match && match[0] !== activeWordIndex) {
108
- setActiveWordIndex(match[0]);
109
- } else if (!match && activeWordIndex !== -1) {
110
- setActiveWordIndex(-1); // Resets when pause/delay happens
111
- }
112
  };
113
 
114
  return (
115
  <div>
116
- <audio ref={audioRef} src={audioUrl} onTimeUpdate={handleTimeUpdate} controls />
117
- <div className="quran-text">
118
- {words.map((word, index) => (
119
- <span key={index} className={index === activeWordIndex ? "text-blue-500 font-bold" : "text-black"}>
120
- {word}
 
 
 
 
 
 
 
 
121
  </span>
122
  ))}
123
  </div>
@@ -126,96 +216,89 @@ const QuranPlayer = ({ audioUrl, timestamps, words }) => {
126
  };
127
  ```
128
 
129
- ### 3. Vue 3 (Composition API)
130
- ```vue
131
- <script setup>
132
- import { ref, onMounted } from 'vue';
133
 
134
- const audioUrl = ref("https://cdn.jsdelivr.net/gh/zaibihsn/recitation-all@main/...opus");
135
- const activeWordIndex = ref(-1);
136
- // Assuming array of Format A timestamps loaded here
137
- const timestamps = ref([[0, 1, 0, 920], [1, 2, 1080, 1440]]);
138
- const words = ref(["Bismillah", "ir-Rahman", "ir-Raheem"]);
139
-
140
- const onTimeUpdate = (event) => {
141
- const currentTimeMs = event.target.currentTime * 1000;
142
-
143
- const match = timestamps.value.find(t => currentTimeMs >= t[2] && currentTimeMs <= t[3]);
144
- activeWordIndex.value = match ? match[0] : -1;
145
- };
146
- </script>
147
-
148
- <template>
149
- <div>
150
- <audio :src="audioUrl" @timeupdate="onTimeUpdate" controls />
151
- <p>
152
- <span
153
- v-for="(word, i) in words"
154
- :key="i"
155
- :class="{ 'highlighted-word': i === activeWordIndex }"
156
- >
157
- {{ word }}
158
- </span>
159
- </p>
160
- </div>
161
- </template>
162
-
163
- <style scoped>
164
- .highlighted-word { color: #3b82f6; font-weight: bold; }
165
- </style>
166
- ```
167
-
168
- ### 4. Flutter (Dart)
169
- Using the popular `just_audio` package.
170
 
171
  ```dart
172
  import 'package:flutter/material.dart';
173
  import 'package:just_audio/just_audio.dart';
 
 
174
 
175
- class QuranPlayerWidget extends StatefulWidget {
176
- final String audioUrl;
177
- final List<dynamic> timestamps; // Parsed JSON
178
- final List<String> words;
179
 
180
- QuranPlayerWidget({required this.audioUrl, required this.timestamps, required this.words});
 
 
 
 
 
 
 
 
 
 
 
181
 
182
  @override
183
- _QuranPlayerWidgetState createState() => _QuranPlayerWidgetState();
184
  }
185
 
186
- class _QuranPlayerWidgetState extends State<QuranPlayerWidget> {
187
  final AudioPlayer _player = AudioPlayer();
 
188
  int _activeWordIndex = -1;
189
 
190
  @override
191
  void initState() {
192
  super.initState();
193
- _initPlayer();
194
  }
195
 
196
- Future<void> _initPlayer() async {
197
- await _player.setUrl(widget.audioUrl);
198
 
 
 
 
 
 
 
 
 
 
 
199
  _player.positionStream.listen((position) {
200
  final currentTimeMs = position.inMilliseconds;
201
- int matchIndex = -1;
 
202
 
203
- for (var t in widget.timestamps) {
204
- // Format A check: [wordIndex, nextIndex, start, end]
205
- if (currentTimeMs >= t[2] && currentTimeMs <= t[3]) {
206
- matchIndex = t[0];
 
207
  break;
208
  }
209
  }
210
 
211
  if (_activeWordIndex != matchIndex) {
212
- setState(() {
213
- _activeWordIndex = matchIndex;
214
- });
215
  }
216
  });
217
  }
218
 
 
 
 
 
 
 
 
 
 
 
219
  @override
220
  void dispose() {
221
  _player.dispose();
@@ -225,13 +308,15 @@ class _QuranPlayerWidgetState extends State<QuranPlayerWidget> {
225
  @override
226
  Widget build(BuildContext context) {
227
  return Wrap(
 
228
  children: widget.words.asMap().entries.map((entry) {
229
- bool isActive = entry.key == _activeWordIndex;
230
  return Text(
231
- entry.value + " ",
232
  style: TextStyle(
233
  color: isActive ? Colors.blue : Colors.black,
234
  fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
 
235
  ),
236
  );
237
  }).toList(),
@@ -240,27 +325,86 @@ class _QuranPlayerWidgetState extends State<QuranPlayerWidget> {
240
  }
241
  ```
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  ---
244
 
245
- ## 🤖 AI Prompt Generator
246
 
247
- If you are using ChatGPT, Claude, GitHub Copilot, or Cursor to build your application, you can copy and paste the prompt below to get an instant, perfectly structured word-by-word active highlighting system tailored to this repository's structure.
248
 
249
- > **Copy this Prompt:**
 
 
 
 
 
 
 
 
 
 
250
  >
251
- > "I am building a Quran application where I need to play audio for a Quran verse and highlight the textual Arabic words as they are being spoken (karaoke style).
252
  >
253
- > The verse audio is hosted via CDN: `https://cdn.jsdelivr.net/gh/zaibihsn/recitation-all@main/{reciter_name}/{surah_padded}/{surah_padded}{verse_padded}.opus`. (E.g., Surah 1 Verse 1 for reciter 'abdul-basit-abdul-samad-murattal-hafs-950' is `.../001/001001.opus`).
254
  >
255
- > The timestamp file is located at the exact same path but with a `.json` extension instead (e.g. `.../001/001001.json`).
256
- > The timestamp JSON could come in one of two formats:
257
- > 1. A flat array of arrays: `[[word_index, next_word_index, start_time_ms, end_time_ms]]`.
258
- > 2. A detailed object: `{"segments": [[word_index, start_time_ms, end_time_ms]]}`.
259
- >
260
- > Please write the UI and logic using **[INSERT YOUR STACK/FRAMEWORK HERE]**.
261
- > Requirements:
262
- > 1. Fetch and parse both timestamp formats safely.
263
- > 2. Initialize an audio player streaming the `.opus` file.
264
- > 3. Track the current playback time of the audio stream in milliseconds.
265
- > 4. Use the timestamp interval logic (`start_time <= current_time <= end_time`) to determine the active active word index.
266
- > 5. Map over a list of placeholder strings (simulating Arabic words) and visually highlight the word that corresponds to the active word index."
 
1
  # Implementation Guide
2
 
3
+ This guide explains how to integrate the Quranic Recitation Dataset into your application using the **Cloudflare Edge CDN** and **Protocol Buffer** timing data.
4
 
5
+ ## 🏗Architecture
6
+
7
+ ```
8
+ ┌─────────────┐ ┌──────────────────────────┐ ┌─────────────────┐
9
+ │ Your App │────▶│ Cloudflare Worker CDN │────▶│ HuggingFace │
10
+ │ (Web/Mobile)│ │ recitation-cdn. │ │ Dataset Repo │
11
+ │ │◀────│ mughalistian.workers.dev │◀────│ │
12
+ └─────────────┘ └──────────────────────────┘ └─────────────────┘
13
+ • Edge caching (1 year)
14
+ • Range requests (206)
15
+ • CORS enabled
16
+ • Slug → folder mapping
17
+ ```
18
+
19
+ ### Per-Surah Model
20
+ Each surah is stored as a **single audio file** (not per-ayah). To play a specific ayah:
21
+ 1. Load the surah `.opus` file
22
+ 2. Parse the `.pb` timing data
23
+ 3. Seek the audio player to the ayah's first word `timestamp_from`
24
+
25
+ This dramatically reduces the number of HTTP requests (from ~6,236 per reciter down to 114) while maintaining word-level precision.
26
 
27
+ ---
28
+
29
+ ## 🗂️ Data Structure
30
 
31
+ ### CDN URL Format
32
+ ```
33
+ https://recitation-cdn.mughalistian.workers.dev/{slug}/{surah_number}.{opus|pb}
34
+ ```
35
 
36
  Where:
37
+ - `{slug}` URL-friendly reciter identifier (see slug map in README.md)
38
+ - `{surah_number}` 3-digit zero-padded surah number (e.g., `001`, `114`)
39
+
40
+ ### Example URLs
41
+ ```bash
42
+ # Audio: Mishari Rashid Al-Afasy, Surah Al-Baqarah
43
+ https://recitation-cdn.mughalistian.workers.dev/mishari-rashid-al-afasy-murattal-hafs/002.opus
44
+
45
+ # Timing: Same reciter, same surah
46
+ https://recitation-cdn.mughalistian.workers.dev/mishari-rashid-al-afasy-murattal-hafs/002.pb
47
+ ```
48
+
49
+ ### Direct HuggingFace Fallback
50
+ If the CDN is unreachable, fall back to the raw HuggingFace URL:
 
 
 
 
 
51
  ```
52
+ https://huggingface.co/datasets/zaibihassan/Quranic-Recitation-Data/resolve/main/{Folder Name}/{Surah}/{File}
53
+ ```
54
+
55
+ > **Note:** The folder names contain spaces and special characters. The CDN handles slug-to-folder mapping automatically.
56
+
57
+ ---
58
+
59
+ ## ⏱️ Protocol Buffer Schema
60
+
61
+ The `.pb` timing files use this schema:
62
+
63
+ ```protobuf
64
+ syntax = "proto3";
65
+ package recitation;
66
+
67
+ message WordSegment {
68
+ int32 word_index_0_based = 1;
69
+ int32 word_index_1_based = 2;
70
+ int32 timestamp_from = 3; // ms from start of surah audio
71
+ int32 timestamp_to = 4; // ms from start of surah audio
72
+ }
73
+
74
+ message VerseSegments {
75
+ repeated WordSegment segments = 1;
76
+ }
77
+
78
+ message SurahTimestamps {
79
+ map<string, VerseSegments> verses = 1; // key = "surah:ayah" e.g. "1:1"
80
  }
81
  ```
82
+
83
+ ### Key Concept
84
+ Timestamps are **relative to the start of the surah audio**. To play ayah 5 of surah 2:
85
+ ```
86
+ seekPosition = verses["2:5"].segments[0].timestamp_from // in milliseconds
87
+ ```
88
 
89
  ---
90
 
91
  ## 💻 Tech Stack Implementations
92
 
93
+ The core pattern across all frameworks:
94
+ 1. Fetch the `.pb` timing data for the surah
95
+ 2. Decode it using a protobuf library
96
+ 3. Load the `.opus` audio file
97
+ 4. Listen to playback position (in milliseconds)
98
+ 5. Find the word where `timestamp_from <= currentTimeMs <= timestamp_to`
99
+ 6. Apply a highlighted style to that word
100
+
101
+ ### 1. JavaScript / TypeScript (Web)
102
 
 
103
  ```javascript
104
+ import protobuf from 'protobufjs';
 
 
105
 
106
+ const CDN_BASE = 'https://recitation-cdn.mughalistian.workers.dev';
 
 
 
 
 
 
 
107
 
108
+ async function loadSurahData(slug, surahNum) {
109
+ const padded = String(surahNum).padStart(3, '0');
110
+
111
+ // Fetch protobuf timing data
112
+ const pbResponse = await fetch(`${CDN_BASE}/${slug}/${padded}.pb`);
113
+ const pbBuffer = await pbResponse.arrayBuffer();
114
+
115
+ // Decode using your compiled protobuf schema
116
+ const root = await protobuf.load('recitation.proto');
117
+ const SurahTimestamps = root.lookupType('recitation.SurahTimestamps');
118
+ const timingData = SurahTimestamps.decode(new Uint8Array(pbBuffer));
119
+
120
+ return timingData;
121
+ }
122
+
123
+ // Audio playback with word highlighting
124
+ const audio = new Audio(`${CDN_BASE}/mishari-rashid-al-afasy-murattal-hafs/001.opus`);
125
+ const timings = await loadSurahData('mishari-rashid-al-afasy-murattal-hafs', 1);
126
+
127
+ let activeWordIndex = -1;
128
+
129
+ audio.addEventListener('timeupdate', () => {
130
+ const currentTimeMs = audio.currentTime * 1000;
131
+ const verseTimings = timings.verses['1:1']; // Current verse
132
+
133
+ if (!verseTimings) return;
134
+
135
+ const match = verseTimings.segments.find(
136
+ seg => currentTimeMs >= seg.timestampFrom && currentTimeMs <= seg.timestampTo
137
+ );
138
+
139
+ if (match && match.wordIndex0Based !== activeWordIndex) {
140
+ activeWordIndex = match.wordIndex0Based;
141
+ highlightWord(activeWordIndex); // Your UI function
142
+ }
143
  });
144
 
145
+ // Seek to a specific ayah
146
+ function seekToAyah(surah, ayah) {
147
+ const key = `${surah}:${ayah}`;
148
+ const verse = timings.verses[key];
149
+ if (verse && verse.segments.length > 0) {
150
+ audio.currentTime = verse.segments[0].timestampFrom / 1000;
151
+ audio.play();
152
+ }
153
+ }
154
+
155
  audio.play();
156
  ```
157
 
158
  ### 2. React.js
159
+
160
  ```tsx
161
  import React, { useState, useEffect, useRef } from 'react';
162
 
163
+ const CDN_BASE = 'https://recitation-cdn.mughalistian.workers.dev';
164
+
165
+ const QuranPlayer = ({ slug, surahNum, words, verseKey }) => {
166
+ const audioRef = useRef<HTMLAudioElement>(null);
167
  const [activeWordIndex, setActiveWordIndex] = useState(-1);
168
+ const [timings, setTimings] = useState(null);
169
+
170
+ const padded = String(surahNum).padStart(3, '0');
171
+
172
+ useEffect(() => {
173
+ // Load protobuf timing data on mount
174
+ fetch(`${CDN_BASE}/${slug}/${padded}.pb`)
175
+ .then(res => res.arrayBuffer())
176
+ .then(buf => {
177
+ // Decode protobuf (using your compiled schema)
178
+ const decoded = SurahTimestamps.decode(new Uint8Array(buf));
179
+ setTimings(decoded);
180
+ });
181
+ }, [slug, surahNum]);
182
 
183
  const handleTimeUpdate = () => {
184
+ if (!audioRef.current || !timings) return;
 
185
  const currentTimeMs = audioRef.current.currentTime * 1000;
186
+ const verse = timings.verses[verseKey];
187
+ if (!verse) return;
188
+
189
+ const match = verse.segments.find(
190
+ s => currentTimeMs >= s.timestampFrom && currentTimeMs <= s.timestampTo
191
  );
192
 
193
+ setActiveWordIndex(match ? match.wordIndex0Based : -1);
 
 
 
 
194
  };
195
 
196
  return (
197
  <div>
198
+ <audio
199
+ ref={audioRef}
200
+ src={`${CDN_BASE}/${slug}/${padded}.opus`}
201
+ onTimeUpdate={handleTimeUpdate}
202
+ controls
203
+ />
204
+ <div className="quran-text" dir="rtl">
205
+ {words.map((word, i) => (
206
+ <span
207
+ key={i}
208
+ className={i === activeWordIndex ? 'text-blue-500 font-bold' : ''}
209
+ >
210
+ {word}{' '}
211
  </span>
212
  ))}
213
  </div>
 
216
  };
217
  ```
218
 
219
+ ### 3. Flutter (Dart)
 
 
 
220
 
221
+ Using `just_audio` and the `protobuf` package:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
  ```dart
224
  import 'package:flutter/material.dart';
225
  import 'package:just_audio/just_audio.dart';
226
+ import 'package:http/http.dart' as http;
227
+ import 'recitation.pb.dart'; // Generated from recitation.proto
228
 
229
+ const cdnBase = 'https://recitation-cdn.mughalistian.workers.dev';
 
 
 
230
 
231
+ class QuranPlayerWidget extends StatefulWidget {
232
+ final String slug;
233
+ final int surahNum;
234
+ final List<String> words;
235
+ final String verseKey; // e.g., "1:1"
236
+
237
+ const QuranPlayerWidget({
238
+ required this.slug,
239
+ required this.surahNum,
240
+ required this.words,
241
+ required this.verseKey,
242
+ });
243
 
244
  @override
245
+ State<QuranPlayerWidget> createState() => _QuranPlayerState();
246
  }
247
 
248
+ class _QuranPlayerState extends State<QuranPlayerWidget> {
249
  final AudioPlayer _player = AudioPlayer();
250
+ SurahTimestamps? _timings;
251
  int _activeWordIndex = -1;
252
 
253
  @override
254
  void initState() {
255
  super.initState();
256
+ _init();
257
  }
258
 
259
+ Future<void> _init() async {
260
+ final padded = widget.surahNum.toString().padLeft(3, '0');
261
 
262
+ // Load protobuf timing data
263
+ final pbUrl = '$cdnBase/${widget.slug}/$padded.pb';
264
+ final response = await http.get(Uri.parse(pbUrl));
265
+ _timings = SurahTimestamps.fromBuffer(response.bodyBytes);
266
+
267
+ // Load audio (supports range requests for seeking)
268
+ final audioUrl = '$cdnBase/${widget.slug}/$padded.opus';
269
+ await _player.setUrl(audioUrl);
270
+
271
+ // Track position for word highlighting
272
  _player.positionStream.listen((position) {
273
  final currentTimeMs = position.inMilliseconds;
274
+ final verse = _timings?.verses[widget.verseKey];
275
+ if (verse == null) return;
276
 
277
+ int matchIndex = -1;
278
+ for (final seg in verse.segments) {
279
+ if (currentTimeMs >= seg.timestampFrom &&
280
+ currentTimeMs <= seg.timestampTo) {
281
+ matchIndex = seg.wordIndex0Based;
282
  break;
283
  }
284
  }
285
 
286
  if (_activeWordIndex != matchIndex) {
287
+ setState(() => _activeWordIndex = matchIndex);
 
 
288
  }
289
  });
290
  }
291
 
292
+ /// Seek to a specific ayah within the loaded surah
293
+ void seekToAyah(String verseKey) {
294
+ final verse = _timings?.verses[verseKey];
295
+ if (verse != null && verse.segments.isNotEmpty) {
296
+ final seekMs = verse.segments.first.timestampFrom;
297
+ _player.seek(Duration(milliseconds: seekMs));
298
+ _player.play();
299
+ }
300
+ }
301
+
302
  @override
303
  void dispose() {
304
  _player.dispose();
 
308
  @override
309
  Widget build(BuildContext context) {
310
  return Wrap(
311
+ textDirection: TextDirection.rtl,
312
  children: widget.words.asMap().entries.map((entry) {
313
+ final isActive = entry.key == _activeWordIndex;
314
  return Text(
315
+ '${entry.value} ',
316
  style: TextStyle(
317
  color: isActive ? Colors.blue : Colors.black,
318
  fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
319
+ fontSize: 28,
320
  ),
321
  );
322
  }).toList(),
 
325
  }
326
  ```
327
 
328
+ ### 4. Swift (iOS)
329
+
330
+ ```swift
331
+ import AVFoundation
332
+
333
+ let cdnBase = "https://recitation-cdn.mughalistian.workers.dev"
334
+
335
+ class QuranPlayer {
336
+ var player: AVPlayer?
337
+ var timings: SurahTimestamps? // Generated from protobuf
338
+ var activeWordIndex: Int = -1
339
+
340
+ func loadSurah(slug: String, surahNum: Int) async {
341
+ let padded = String(format: "%03d", surahNum)
342
+
343
+ // Load audio with range request support
344
+ let audioURL = URL(string: "\(cdnBase)/\(slug)/\(padded).opus")!
345
+ player = AVPlayer(url: audioURL)
346
+
347
+ // Load protobuf timing
348
+ let pbURL = URL(string: "\(cdnBase)/\(slug)/\(padded).pb")!
349
+ let (data, _) = try! await URLSession.shared.data(from: pbURL)
350
+ timings = try! SurahTimestamps(serializedBytes: data)
351
+
352
+ // Observe playback position
353
+ player?.addPeriodicTimeObserver(
354
+ forInterval: CMTime(value: 1, timescale: 30),
355
+ queue: .main
356
+ ) { [weak self] time in
357
+ self?.updateHighlight(currentTimeMs: Int(time.seconds * 1000))
358
+ }
359
+ }
360
+
361
+ func seekToAyah(_ verseKey: String) {
362
+ guard let verse = timings?.verses[verseKey],
363
+ let firstSeg = verse.segments.first else { return }
364
+ let seekTime = CMTime(value: Int64(firstSeg.timestampFrom), timescale: 1000)
365
+ player?.seek(to: seekTime)
366
+ player?.play()
367
+ }
368
+
369
+ private func updateHighlight(currentTimeMs: Int) {
370
+ // Find active word in current verse's segments
371
+ guard let verse = timings?.verses["1:1"] else { return }
372
+
373
+ for seg in verse.segments {
374
+ if currentTimeMs >= seg.timestampFrom && currentTimeMs <= seg.timestampTo {
375
+ activeWordIndex = Int(seg.wordIndex0Based)
376
+ return
377
+ }
378
+ }
379
+ }
380
+ }
381
+ ```
382
+
383
  ---
384
 
385
+ ## 🤖 AI Prompt Template
386
 
387
+ Copy this prompt into ChatGPT, Claude, or Copilot to scaffold your integration:
388
 
389
+ > I am building a Quran application with **word-by-word audio highlighting** (karaoke style).
390
+ >
391
+ > **CDN Base URL:** `https://recitation-cdn.mughalistian.workers.dev`
392
+ > **URL Format:** `{CDN_BASE}/{reciter-slug}/{surah_padded}.opus` (audio) and `.pb` (timing)
393
+ >
394
+ > The timing data is a Protocol Buffer file using this schema:
395
+ > ```protobuf
396
+ > message WordSegment { int32 word_index_0_based=1; int32 word_index_1_based=2; int32 timestamp_from=3; int32 timestamp_to=4; }
397
+ > message VerseSegments { repeated WordSegment segments=1; }
398
+ > message SurahTimestamps { map<string, VerseSegments> verses=1; }
399
+ > ```
400
  >
401
+ > Each surah is a **single audio file**. Timestamps are in **milliseconds from the start of the surah audio**. The `.pb` file contains all verses of that surah.
402
  >
403
+ > To play a specific ayah, seek the audio player to `verses["surah:ayah"].segments[0].timestamp_from` ms.
404
  >
405
+ > Please write the complete implementation using **[YOUR FRAMEWORK]**:
406
+ > 1. Fetch and decode the `.pb` file
407
+ > 2. Stream the `.opus` audio with seeking support
408
+ > 3. Track playback position in milliseconds
409
+ > 4. Highlight the active word using `timestamp_from <= currentMs <= timestamp_to`
410
+ > 5. Support seeking to any ayah within the surah