JSFiddle - React, Tailwind, and code Playground
HTML
<audio controls id="audio" src=""></audio>
<span id="author"></span>
JavaScript
// Step 1: Search for the file
const searchWord = "vert";
const searchString = `\-${searchWord}.wav`; // double escape `\\-` so to passe one escape `\-` down
const ISO = `fra`; // example iso
const searchCategory = `incategory%3A%22Lingua_Libre_pronunciation-${ISO}%22`;
const searchURL = `https://commons.wikimedia.org/w/api.php?action=query&format=json&list=search&srsearch=${searchString}&srnamespace=6&origin=*`;
const advancedURL=`https://commons.wikimedia.org/w/api.php?action=query&format=json&list=search&srsearch=intitle:/${searchString}/i%20${searchCategory}&srnamespace=6&origin=*`
// for regex, use : intitle:/${searchString}/ , but then remove an escape in searchString's `\\-`
console.log({ searchWord })
console.log({ searchString })
console.log({ searchCategory })
console.log({ searchURL }) // all languages > word `*-hund.wav`
console.log({ advancedURL }) // target language `nor` > word `*-hund.wav`
fetch(advancedURL)
.then(response => response.json())
.then(data => {
if (data.query.search.length > 0) {
// Get the title of the first search result
const pageTitle = data.query.search[0].title;
console.log({ pageTitle })
// Step 2: Get the media file URL using the title
const fileInfoURL = `https://commons.wikimedia.org/w/api.php?action=query&format=json&titles=${encodeURIComponent(pageTitle)}&prop=imageinfo&iiprop=user|url&origin=*`;
console.log({ fileInfoURL })
return fetch(fileInfoURL)
.then(response => response.json())
.then(data => {
// Extract the URL from the response
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
const fileUrl = pages[pageId].imageinfo[0].url;
const fileUser = pages[pageId].imageinfo[0].user;
document.getElementById('audio').src = fileUrl;
document.getElementById('author').innerHTML = fileUser;
console.log('Media file URL:', fileUrl);
});
} else {
...