I am using MediaElement.js library to add marker to audio timeline. I am trying to fetch data from JSON file, converting it into an array and (unsuccessfully) using it as one of the parameter.
My JSON data is as follows:
{
"StartTimeInMin": "0",
"EndTimeInMin": "60",
"event": [{
"EventTimeMin": "4",
"EventType": "1"
}, {
"EventTimeMin": "10",
"EventType": "2"
}]
}
It can also be accessed from: https://api.myjson.com/bins/y2v0k
My code to fetch the data:
let minuteMarkers = [];
function getJson() {
fetch("https://api.myjson.com/bins/y2v0k")
.then(function (res) {
return res.json();
})
.then(function (data) {
parsingdata = JSON.parse(data);
console.log(parsingdata);
jsondata = data.event;
jsondata.forEach(function (e) {
minuteMarkers.push(e.EventTimeMin);
return minuteMarkers;
});
})
.catch(function (err) {
console.log(err);
});
}
getJson();
console.log(minuteMarkers);
let player = new MediaElementPlayer("player2", {
features: [
"playpause",
"current",
"progress",
"duration",
"markers",
"fullscreen"
],
// markers: ["4", "14"], <- it works
markers: minuteMarkers, // <- This does not work !
markerColor: "#00FF00",
markerCallback: function (media, time) {
alert(time);
}
});
When I did console.log(minuteMarkers), I got [] as result. I was expecting to get ["4", "10"].
One of the problem that I could think is: The fetch is giving me data after "player" variable runs. Hence while executing "player" it does not have "minuteMarker" and I am not getting the result.
Requesting your help to get the data as an array and feed to the player-> marker.
Thanks
Remember that is an asynchronous call, so your code should be inside the promise.
For example:
function getJson() {
fetch("https://api.myjson.com/bins/y2v0k")
.then(function (res) {
return res.json();
})
.then(function (data) {
let minuteMarkers = [];
data.event.forEach(function (item) {
minuteMarkers.push(item.EventTimeMin);
});
createPlayer(minuteMarkers);
})
.catch(function (err) {
console.log(err);
});
}
function createPlayer(minuteMarkers) {
let player = new MediaElementPlayer("player2", {
features: [
"playpause",
"current",
"progress",
"duration",
"markers",
"fullscreen"
],
markers: minuteMarkers,
markerColor: "#00FF00",
markerCallback: function (media, time) {
alert(time);
}
});
}
getJson();