File size: 12,753 Bytes
96d1be7
 
df7f952
96d1be7
df7f952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d1be7
df7f952
 
 
96d1be7
df7f952
 
5b7fda1
df7f952
96d1be7
 
df7f952
 
 
 
 
 
5b7fda1
df7f952
 
5b7fda1
df7f952
 
 
 
96d1be7
df7f952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d1be7
 
df7f952
 
 
 
 
 
96d1be7
 
 
 
 
df7f952
 
 
 
 
 
 
 
 
96d1be7
 
df7f952
96d1be7
5b7fda1
96d1be7
df7f952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d1be7
 
df7f952
 
 
 
 
 
 
 
 
 
96d1be7
 
 
 
df7f952
96d1be7
 
 
5b7fda1
df7f952
 
 
96d1be7
df7f952
 
 
 
 
 
 
 
 
 
 
 
 
 
96d1be7
 
df7f952
96d1be7
df7f952
 
 
 
 
96d1be7
 
df7f952
96d1be7
 
 
 
df7f952
 
 
 
 
 
 
 
 
 
 
 
 
96d1be7
 
 
 
 
 
 
 
df7f952
96d1be7
df7f952
96d1be7
 
 
 
df7f952
 
96d1be7
5b7fda1
96d1be7
df7f952
 
 
 
 
 
 
 
 
 
 
 
96d1be7
 
df7f952
96d1be7
 
df7f952
96d1be7
df7f952
96d1be7
 
 
 
 
df7f952
96d1be7
 
df7f952
 
96d1be7
df7f952
 
 
 
 
 
 
 
 
 
96d1be7
 
df7f952
 
96d1be7
df7f952
 
 
 
 
96d1be7
 
 
 
 
df7f952
96d1be7
 
 
 
df7f952
 
 
 
 
 
 
 
 
 
96d1be7
 
 
 
 
 
 
 
 
df7f952
96d1be7
df7f952
96d1be7
df7f952
96d1be7
 
 
df7f952
96d1be7
 
 
 
 
 
 
 
df7f952
 
 
 
 
5b7fda1
df7f952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96d1be7
 
df7f952
96d1be7
df7f952
96d1be7
df7f952
 
5b7fda1
df7f952
 
 
 
 
 
 
 
96d1be7
df7f952
96d1be7
df7f952
96d1be7
df7f952
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# Implementation Guide

This guide explains how to integrate the Quranic Recitation Dataset into your application using the **Cloudflare Edge CDN** and **Protocol Buffer** timing data.

## πŸ—οΈ Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Your App   │────▢│  Cloudflare Worker CDN   │────▢│   HuggingFace   β”‚
β”‚  (Web/Mobile)β”‚     β”‚  recitation-cdn.         β”‚     β”‚   Dataset Repo  β”‚
β”‚             │◀────│  mughalistian.workers.dev │◀────│                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β€’ Edge caching (1 year)
                    β€’ Range requests (206)
                    β€’ CORS enabled
                    β€’ Slug β†’ folder mapping
```

### Per-Surah Model
Each surah is stored as a **single audio file** (not per-ayah). To play a specific ayah:
1. Load the surah `.opus` file
2. Parse the `.pb` timing data
3. Seek the audio player to the ayah's first word `timestamp_from`

This dramatically reduces the number of HTTP requests (from ~6,236 per reciter down to 114) while maintaining word-level precision.

---

## πŸ—‚οΈ Data Structure

### CDN URL Format
```
https://cdn.mualim.app/{slug}/{surah_number}.{opus|pb}
```

Where:
- `{slug}` β€” URL-friendly reciter identifier (see slug map in README.md)
- `{surah_number}` β€” 3-digit zero-padded surah number (e.g., `001`, `114`)

### Example URLs
```bash
# Audio: Mishari Rashid Al-Afasy, Surah Al-Baqarah
https://cdn.mualim.app/mishari-rashid-al-afasy-murattal-hafs/002.opus

# Timing: Same reciter, same surah
https://cdn.mualim.app/mishari-rashid-al-afasy-murattal-hafs/002.pb
```

### Direct HuggingFace Fallback
If the CDN is unreachable, fall back to the raw HuggingFace URL:
```
https://huggingface.co/datasets/zaibihassan/Quranic-Recitation-Data/resolve/main/{Folder Name}/{Surah}/{File}
```

> **Note:** The folder names contain spaces and special characters. The CDN handles slug-to-folder mapping automatically.

---

## ⏱️ Protocol Buffer Schema

The `.pb` timing files use this schema:

```protobuf
syntax = "proto3";
package recitation;

message WordSegment {
  int32 word_index_0_based = 1;
  int32 word_index_1_based = 2;
  int32 timestamp_from = 3;      // ms from start of surah audio
  int32 timestamp_to = 4;        // ms from start of surah audio
}

message VerseSegments {
  repeated WordSegment segments = 1;
}

message SurahTimestamps {
  map<string, VerseSegments> verses = 1;  // key = "surah:ayah" e.g. "1:1"
}
```

### Key Concept
Timestamps are **relative to the start of the surah audio**. To play ayah 5 of surah 2:
```
seekPosition = verses["2:5"].segments[0].timestamp_from  // in milliseconds
```

---

## πŸ’» Tech Stack Implementations

The core pattern across all frameworks:
1. Fetch the `.pb` timing data for the surah
2. Decode it using a protobuf library
3. Load the `.opus` audio file
4. Listen to playback position (in milliseconds)
5. Find the word where `timestamp_from <= currentTimeMs <= timestamp_to`
6. Apply a highlighted style to that word

### 1. JavaScript / TypeScript (Web)

```javascript
import protobuf from 'protobufjs';

const CDN_BASE = 'https://cdn.mualim.app';

async function loadSurahData(slug, surahNum) {
  const padded = String(surahNum).padStart(3, '0');
  
  // Fetch protobuf timing data
  const pbResponse = await fetch(`${CDN_BASE}/${slug}/${padded}.pb`);
  const pbBuffer = await pbResponse.arrayBuffer();
  
  // Decode using your compiled protobuf schema
  const root = await protobuf.load('recitation.proto');
  const SurahTimestamps = root.lookupType('recitation.SurahTimestamps');
  const timingData = SurahTimestamps.decode(new Uint8Array(pbBuffer));
  
  return timingData;
}

// Audio playback with word highlighting
const audio = new Audio(`${CDN_BASE}/mishari-rashid-al-afasy-murattal-hafs/001.opus`);
const timings = await loadSurahData('mishari-rashid-al-afasy-murattal-hafs', 1);

let activeWordIndex = -1;

audio.addEventListener('timeupdate', () => {
  const currentTimeMs = audio.currentTime * 1000;
  const verseTimings = timings.verses['1:1']; // Current verse
  
  if (!verseTimings) return;
  
  const match = verseTimings.segments.find(
    seg => currentTimeMs >= seg.timestampFrom && currentTimeMs <= seg.timestampTo
  );
  
  if (match && match.wordIndex0Based !== activeWordIndex) {
    activeWordIndex = match.wordIndex0Based;
    highlightWord(activeWordIndex); // Your UI function
  }
});

// Seek to a specific ayah
function seekToAyah(surah, ayah) {
  const key = `${surah}:${ayah}`;
  const verse = timings.verses[key];
  if (verse && verse.segments.length > 0) {
    audio.currentTime = verse.segments[0].timestampFrom / 1000;
    audio.play();
  }
}

audio.play();
```

### 2. React.js

```tsx
import React, { useState, useEffect, useRef } from 'react';

const CDN_BASE = 'https://cdn.mualim.app';

const QuranPlayer = ({ slug, surahNum, words, verseKey }) => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [activeWordIndex, setActiveWordIndex] = useState(-1);
  const [timings, setTimings] = useState(null);

  const padded = String(surahNum).padStart(3, '0');

  useEffect(() => {
    // Load protobuf timing data on mount
    fetch(`${CDN_BASE}/${slug}/${padded}.pb`)
      .then(res => res.arrayBuffer())
      .then(buf => {
        // Decode protobuf (using your compiled schema)
        const decoded = SurahTimestamps.decode(new Uint8Array(buf));
        setTimings(decoded);
      });
  }, [slug, surahNum]);

  const handleTimeUpdate = () => {
    if (!audioRef.current || !timings) return;
    const currentTimeMs = audioRef.current.currentTime * 1000;
    const verse = timings.verses[verseKey];
    if (!verse) return;

    const match = verse.segments.find(
      s => currentTimeMs >= s.timestampFrom && currentTimeMs <= s.timestampTo
    );

    setActiveWordIndex(match ? match.wordIndex0Based : -1);
  };

  return (
    <div>
      <audio
        ref={audioRef}
        src={`${CDN_BASE}/${slug}/${padded}.opus`}
        onTimeUpdate={handleTimeUpdate}
        controls
      />
      <div className="quran-text" dir="rtl">
        {words.map((word, i) => (
          <span
            key={i}
            className={i === activeWordIndex ? 'text-blue-500 font-bold' : ''}
          >
            {word}{' '}
          </span>
        ))}
      </div>
    </div>
  );
};
```

### 3. Flutter (Dart)

Using `just_audio` and the `protobuf` package:

```dart
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:http/http.dart' as http;
import 'recitation.pb.dart'; // Generated from recitation.proto

const cdnBase = 'https://cdn.mualim.app';

class QuranPlayerWidget extends StatefulWidget {
  final String slug;
  final int surahNum;
  final List<String> words;
  final String verseKey; // e.g., "1:1"

  const QuranPlayerWidget({
    required this.slug,
    required this.surahNum,
    required this.words,
    required this.verseKey,
  });

  @override
  State<QuranPlayerWidget> createState() => _QuranPlayerState();
}

class _QuranPlayerState extends State<QuranPlayerWidget> {
  final AudioPlayer _player = AudioPlayer();
  SurahTimestamps? _timings;
  int _activeWordIndex = -1;

  @override
  void initState() {
    super.initState();
    _init();
  }

  Future<void> _init() async {
    final padded = widget.surahNum.toString().padLeft(3, '0');
    
    // Load protobuf timing data
    final pbUrl = '$cdnBase/${widget.slug}/$padded.pb';
    final response = await http.get(Uri.parse(pbUrl));
    _timings = SurahTimestamps.fromBuffer(response.bodyBytes);

    // Load audio (supports range requests for seeking)
    final audioUrl = '$cdnBase/${widget.slug}/$padded.opus';
    await _player.setUrl(audioUrl);

    // Track position for word highlighting
    _player.positionStream.listen((position) {
      final currentTimeMs = position.inMilliseconds;
      final verse = _timings?.verses[widget.verseKey];
      if (verse == null) return;

      int matchIndex = -1;
      for (final seg in verse.segments) {
        if (currentTimeMs >= seg.timestampFrom && 
            currentTimeMs <= seg.timestampTo) {
          matchIndex = seg.wordIndex0Based;
          break;
        }
      }

      if (_activeWordIndex != matchIndex) {
        setState(() => _activeWordIndex = matchIndex);
      }
    });
  }

  /// Seek to a specific ayah within the loaded surah
  void seekToAyah(String verseKey) {
    final verse = _timings?.verses[verseKey];
    if (verse != null && verse.segments.isNotEmpty) {
      final seekMs = verse.segments.first.timestampFrom;
      _player.seek(Duration(milliseconds: seekMs));
      _player.play();
    }
  }

  @override
  void dispose() {
    _player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Wrap(
      textDirection: TextDirection.rtl,
      children: widget.words.asMap().entries.map((entry) {
        final isActive = entry.key == _activeWordIndex;
        return Text(
          '${entry.value} ',
          style: TextStyle(
            color: isActive ? Colors.blue : Colors.black,
            fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
            fontSize: 28,
          ),
        );
      }).toList(),
    );
  }
}
```

### 4. Swift (iOS)

```swift
import AVFoundation

let cdnBase = "https://cdn.mualim.app"

class QuranPlayer {
    var player: AVPlayer?
    var timings: SurahTimestamps?  // Generated from protobuf
    var activeWordIndex: Int = -1
    
    func loadSurah(slug: String, surahNum: Int) async {
        let padded = String(format: "%03d", surahNum)
        
        // Load audio with range request support
        let audioURL = URL(string: "\(cdnBase)/\(slug)/\(padded).opus")!
        player = AVPlayer(url: audioURL)
        
        // Load protobuf timing
        let pbURL = URL(string: "\(cdnBase)/\(slug)/\(padded).pb")!
        let (data, _) = try! await URLSession.shared.data(from: pbURL)
        timings = try! SurahTimestamps(serializedBytes: data)
        
        // Observe playback position
        player?.addPeriodicTimeObserver(
            forInterval: CMTime(value: 1, timescale: 30),
            queue: .main
        ) { [weak self] time in
            self?.updateHighlight(currentTimeMs: Int(time.seconds * 1000))
        }
    }
    
    func seekToAyah(_ verseKey: String) {
        guard let verse = timings?.verses[verseKey],
              let firstSeg = verse.segments.first else { return }
        let seekTime = CMTime(value: Int64(firstSeg.timestampFrom), timescale: 1000)
        player?.seek(to: seekTime)
        player?.play()
    }
    
    private func updateHighlight(currentTimeMs: Int) {
        // Find active word in current verse's segments
        guard let verse = timings?.verses["1:1"] else { return }
        
        for seg in verse.segments {
            if currentTimeMs >= seg.timestampFrom && currentTimeMs <= seg.timestampTo {
                activeWordIndex = Int(seg.wordIndex0Based)
                return
            }
        }
    }
}
```

---

## πŸ€– AI Prompt Template

Copy this prompt into ChatGPT, Claude, or Copilot to scaffold your integration:

> I am building a Quran application with **word-by-word audio highlighting** (karaoke style).
> 
> **CDN Base URL:** `https://cdn.mualim.app`
> **URL Format:** `{CDN_BASE}/{reciter-slug}/{surah_padded}.opus` (audio) and `.pb` (timing)
> 
> The timing data is a Protocol Buffer file using this schema:
> ```protobuf
> message WordSegment { int32 word_index_0_based=1; int32 word_index_1_based=2; int32 timestamp_from=3; int32 timestamp_to=4; }
> message VerseSegments { repeated WordSegment segments=1; }
> message SurahTimestamps { map<string, VerseSegments> verses=1; }
> ```
> 
> 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.
> 
> To play a specific ayah, seek the audio player to `verses["surah:ayah"].segments[0].timestamp_from` ms.
> 
> Please write the complete implementation using **[YOUR FRAMEWORK]**:
> 1. Fetch and decode the `.pb` file
> 2. Stream the `.opus` audio with seeking support
> 3. Track playback position in milliseconds
> 4. Highlight the active word using `timestamp_from <= currentMs <= timestamp_to`
> 5. Support seeking to any ayah within the surah