# Audio Integration Architecture
## 1. Audio URL Construction
Audio is one file per ayah. **Files are named by the global ayah number (1 to 6236, counted through the whole Quran), not by the surah number**: `114.mp3` is the 114th ayah of the Quran (inside Al-Baqarah), not Surah An-Nas. Surah 114 starts at global ayah 6231.
```
https://audio.globalquran.com/{recitorId}/{mp3|ogg}/{kbs}kbs/{globalAyah}.{mp3|ogg}
https://audio.globalquran.com/ar.alafasy/mp3/128kbs/262.mp3 (Ayat al-Kursi, 2:255)
```
Global ayah number = `start_ayah` of the surah (from `/v1/surah`) + ayah number - 1.
```javascript
// Step 3: Build audio URLs
function globalAyah(surah, ayahNumber) {
return surah.startAyah + ayahNumber - 1; // startAyah comes from /v1/surah (start_ayah)
}
// A recitor's "media" (from /v2/list/recitor) is an object like { "mp3-128": {kbs, type, status, auz}, "ogg-64": {...} }.
// Return the usable variants, best first. Try the next one if a file fails to load: a listed variant is not
// guaranteed to exist for every ayah.
function audioVariants(media) {
const probe = document.createElement('audio');
const canOgg = probe.canPlayType('audio/ogg; codecs="vorbis"') !== '';
return Object.values(media)
.filter(m => m.status === 'active' && (m.type === 'mp3' || (m.type === 'ogg' && canOgg)))
.sort((a, b) => (a.type === 'mp3' ? 0 : 1) - (b.type === 'mp3' ? 0 : 1) || Number(b.kbs) - Number(a.kbs)); // mp3 first (plays everywhere), highest bitrate first
}
function buildAudioUrl(recitorId, globalAyahNumber, variant) {
return `https://audio.globalquran.com/${recitorId}/${variant.type}/${variant.kbs}kbs/${globalAyahNumber}.${variant.type}`;
}
// Optional: the "A'udhu billah" (seeking refuge) recording. Only recitors whose media entries have an "auz" field have it:
// https://audio.globalquran.com/{recitorId}/{type}/{kbs}kbs/0.{type}
```
## 3. Bismillah Logic Explanation
The Bismillah is not a separate recording: it is the audio of the very first ayah of the Quran (Al-Fatiha 1:1), global ayah number 1, so its file is always named `1`.
### Bismillah Rules:
- **Al-Fatiha (Surah 1)**: the Bismillah IS its first ayah (1:1). Play the surah normally and do not add another Bismillah in front of it.
- **At-Tawbah (Surah 9)**: has no Bismillah (the API marks it with `skip_bismillah: true`).
- **All other surahs**: the Bismillah is recited before the first ayah, so play file `1` first, then the surah's real first ayah.
- If a listener chooses to start from a specific ayah ("play from here"), do not add the Bismillah.
### Playback Flow:
1. **Check if the surah needs a Bismillah**: `surahNumber !== 1 && !surah.skipBismillah`
2. **If yes and starting from the top**: play global ayah 1 first
3. **After the Bismillah**: play the actual first ayah of the surah
4. **Continue**: normal ayah-by-ayah progression
5. **Next surah**: work out again whether it needs a Bismillah and repeat
### Audio URL Construction:
- **Bismillah**: `https://audio.globalquran.com/{recitorId}/{type}/{kbs}kbs/1.{type}`
- **Actual Ayah**: `https://audio.globalquran.com/{recitorId}/{type}/{kbs}kbs/{globalAyah}.{type}` where `globalAyah = start_ayah + ayah - 1`
## 2. Advanced Audio Player Implementation
```javascript
// Step 4: Implement advanced audio player with ayah/surah progression
class QuranAudioPlayer {
constructor() {
this.currentAudio = null;
this.currentSurah = null;
this.currentAyah = null;
this.currentRecitor = null;
this.variants = []; // usable audio variants of the current recitor, best first
this.variantIndex = 0;
this.surahs = []; // normalised surah list (see initializeApp)
this.surahData = null;
this.isPlaying = false;
this.shouldPlayBismillah = false;
this.bismillahPlayed = false;
}
setSurahs(surahs) {
this.surahs = surahs;
}
// The Bismillah goes in front of every surah except Al-Fatiha (its ayah 1 IS the Bismillah) and At-Tawbah (none)
needsBismillah(surah) {
return surah.number !== 1 && !surah.skipBismillah;
}
async playSurah(recitorId, surahNumber, media, surahData) {
// Stop current audio if playing
this.stop();
this.currentRecitor = recitorId;
this.currentSurah = surahNumber;
this.currentAyah = 1;
this.variants = audioVariants(media);
this.variantIndex = 0;
this.surahData = surahData;
this.bismillahPlayed = false;
// Determine if we should play Bismillah
this.shouldPlayBismillah = this.needsBismillah(surahData);
// Start playing
await this.playCurrentAyah();
}
async playCurrentAyah() {
if (!this.currentRecitor || !this.currentSurah || !this.currentAyah) {
return;
}
// Stop current audio
if (this.currentAudio) {
this.currentAudio.pause();
this.currentAudio = null;
}
let globalNumber;
// Check if we need to play Bismillah first
if (this.shouldPlayBismillah && !this.bismillahPlayed && this.currentAyah === 1) {
// The Bismillah is the audio of global ayah 1 (Al-Fatiha 1:1)
globalNumber = 1;
this.bismillahPlayed = true;
} else {
// Play the actual ayah: files are numbered through the whole Quran
globalNumber = globalAyah(this.surahData, this.currentAyah);
}
await this.playFile(globalNumber);
}
async playFile(globalNumber) {
const variant = this.variants[this.variantIndex];
if (!variant) {
console.error('No playable audio variant for this recitor');
return;
}
// Create and play new audio
this.currentAudio = new Audio(buildAudioUrl(this.currentRecitor, globalNumber, variant));
this.currentAudio.crossOrigin = 'anonymous';
// Set up event listeners
this.currentAudio.addEventListener('ended', () => {
this.onAyahEnded();
});
this.currentAudio.addEventListener('error', (error) => {
console.error('Audio playback error:', error);
// The file may not exist in this variant: try the next one before giving up on the ayah
if (this.variantIndex + 1 < this.variants.length) {
this.variantIndex++;
this.playFile(globalNumber);
} else {
this.variantIndex = 0;
this.onAyahEnded(); // Try to continue to next ayah
}
});
try {
await this.currentAudio.play();
this.isPlaying = true;
// Update UI to show current ayah
this.updateCurrentAyahDisplay();
} catch (error) {
console.error('Audio playback failed:', error);
this.onAyahEnded(); // Try to continue to next ayah
}
}
onAyahEnded() {
this.isPlaying = false;
// If we just played Bismillah, now play the actual first ayah
if (this.shouldPlayBismillah && this.bismillahPlayed && this.currentAyah === 1) {
// Bismillah finished, now play actual first ayah
this.playCurrentAyah();
return;
}
// Move to next ayah
this.currentAyah++;
// Check if we've finished all ayahs in current surah
if (this.currentAyah > this.surahData.numberOfAyahs) {
// Move to next surah
this.currentSurah++;
this.currentAyah = 1;
this.bismillahPlayed = false;
// Check if we've finished all surahs
if (this.currentSurah > 114) {
this.stop();
this.onPlaybackComplete();
return;
}
// Update surah data for the new surah (and whether it needs a Bismillah)
this.loadSurahData(this.currentSurah);
this.shouldPlayBismillah = this.needsBismillah(this.surahData);
}
// Continue playing
this.playCurrentAyah();
}
loadSurahData(surahNumber) {
// The list was loaded once at start-up (see initializeApp): no new request is needed
this.surahData = this.surahs.find(surah => surah.number === surahNumber);
// Update UI with new surah info
this.updateSurahDisplay();
}
pause() {
if (this.currentAudio && this.isPlaying) {
this.currentAudio.pause();
this.isPlaying = false;
}
}
resume() {
if (this.currentAudio && !this.isPlaying) {
this.currentAudio.play().then(() => {
this.isPlaying = true;
}).catch(error => {
console.error('Failed to resume audio:', error);
});
}
}
stop() {
if (this.currentAudio) {
this.currentAudio.pause();
this.currentAudio.currentTime = 0;
this.currentAudio = null;
}
this.isPlaying = false;
}
skipToAyah(ayahNumber) {
if (ayahNumber >= 1 && ayahNumber <= this.surahData.numberOfAyahs) {
this.currentAyah = ayahNumber;
this.bismillahPlayed = true; // The listener chose this ayah: no Bismillah in front of it
this.playCurrentAyah();
}
}
skipToSurah(surahNumber) {
if (surahNumber >= 1 && surahNumber <= 114) {
this.currentSurah = surahNumber;
this.currentAyah = 1;
this.bismillahPlayed = false;
this.loadSurahData(surahNumber);
this.playCurrentAyah();
}
}
updateCurrentAyahDisplay() {
// Update UI to highlight current ayah
const ayahElement = document.querySelector(`[data-ayah="${this.currentAyah}"]`);
if (ayahElement) {
// Remove previous highlights
document.querySelectorAll('.ayah-playing').forEach(el => {
el.classList.remove('ayah-playing');
});
// Highlight current ayah
ayahElement.classList.add('ayah-playing');
ayahElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
updateSurahDisplay() {
// Update UI to show current surah
const surahElement = document.querySelector(`[data-surah="${this.currentSurah}"]`);
if (surahElement) {
// Remove previous highlights
document.querySelectorAll('.surah-playing').forEach(el => {
el.classList.remove('surah-playing');
});
// Highlight current surah
surahElement.classList.add('surah-playing');
}
}
onPlaybackComplete() {
// Called when all surahs are finished
console.log('Playback completed - all surahs finished');
// Update UI
document.querySelectorAll('.ayah-playing, .surah-playing').forEach(el => {
el.classList.remove('ayah-playing', 'surah-playing');
});
// Show completion message
this.showCompletionMessage();
}
showCompletionMessage() {
// Show completion notification
const notification = document.createElement('div');
notification.className = 'playback-complete-notification';
notification.innerHTML = `
<div style="background: #28a745; color: white; padding: 15px; border-radius: 8px; margin: 10px;">
<i class="fas fa-check-circle"></i>
Playback Complete - All 114 Surahs Finished!
</div>
`;
document.body.appendChild(notification);
// Remove notification after 5 seconds
setTimeout(() => {
notification.remove();
}, 5000);
}
// Get current playback status
getStatus() {
return {
isPlaying: this.isPlaying,
currentSurah: this.currentSurah,
currentAyah: this.currentAyah,
currentRecitor: this.currentRecitor,
shouldPlayBismillah: this.shouldPlayBismillah,
bismillahPlayed: this.bismillahPlayed
};
}
}
```