Oliver Sewell Oliver Sewell - 3 years ago 183
HTML Question

how do i get audio files out of collection.json

How do i get the mp3 audio link out of this collection.json.
i want to get it so when a user searches in the search box the audio files pop up to play but i'm a little confused

enter image description here

enter image description here

Here is my code so far



const media = 'audio';
const searchInput = document.querySelector('.search');
const output = document.querySelector('.output')

searchInput.addEventListener('change', searchData);

async function searchData() {
let search = this.value;
const finalData = await getData(search);
render(finalData);
}

function render(data) {
let html;
if(media == 'image') {
html = data.map(result => {
return `
<div class="image">
<img src="${result.links[0].href}"/>
</div>
`
}).join("");
} else {
//parse the json
console.log(data);
data.map(result => {
console.log(result);
})
/* i want to get the mp3 audio out of the collection.json , how do i do this please? */

}
output.innerHTML = html;

}

function getData(search) {
const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;

return fetch(endpoint)
.then(blob => blob.json())
.then(data => data.collection.items);
}

<input type="text" class="search" placeholder="planet">
<div class="output"></div>





Thank you in advance

Answer Source

You're only doing a query to get the API data, which is returning a collection of objects, each only describing a resource.

For each resource, to get a URL for an actual MP3, you need to do another fetch for the collection.json file, at the URL provided in the href field. This will return the contents of that JSON file, which in this case is an array of URLs to yet more files, some of which are mp3s. You'll need to then find a URL in that array that ends with .mp3 and set that as the src of an <audio> element.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download