# 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 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(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 (
); }; ``` ### 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 words; final String verseKey; // e.g., "1:1" const QuranPlayerWidget({ required this.slug, required this.surahNum, required this.words, required this.verseKey, }); @override State createState() => _QuranPlayerState(); } class _QuranPlayerState extends State { final AudioPlayer _player = AudioPlayer(); SurahTimestamps? _timings; int _activeWordIndex = -1; @override void initState() { super.initState(); _init(); } Future _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 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