@speechkit/speechkit-audio-player
Version:
A web player component that can play audio from https://speechkit.io
63 lines (58 loc) • 1.98 kB
JavaScript
import { fetchWithErrorHandling } from '../utils/BetterFetch'
class PodcastResolver {
constructor(options) {
this.apiKey = options.apiKey;
this.skBackend = options.skBackend;
this.projectId = options.projectId;
}
resolve(url) {
return new Promise((resolve, reject) => {
//request the audio using ID and api-key in headers
const sUrl = `${this.skBackend}/s/${this.projectId}/${encodeURIComponent(url)}`
return fetchWithErrorHandling(sUrl, {
headers: {
'Authorization': `Token token=${this.apiKey}`,
}
})
// get and return json from the response
.then(response => response.json())
// return audio object if there are media files present and resolve promise
.then(oJson => {
if (oJson.media && oJson.media.length) {
return resolve(oJson);
}
throw new Error('Resolve JSON error');
})
.catch(error => {
reject();
console.log('Resolve error: Cannot find audio for this article: ' + error);
});
});
}
// Load the next audio using audio_id, (passed in)
loadNext(audioId) {
return new Promise((resolve, reject) => {
//request the audio using ID and api-key in headers
const sUrl = `/api/v2/projects/${this.projectId}/podcasts/${audioId}`
return fetchWithErrorHandling(sUrl, {
headers: {
'Authorization': `Token token=${this.apiKey}`,
}
})
// get and return json from the response (if valid)
.then(response => response.json())
// return audio object if there are media files present and resolve promise
.then(oJson => {
if (oJson.media && oJson.media.length) {
return resolve(oJson);
}
throw new Error('LoadNextAudio JSON error' + oJson);
})
.catch(error => {
reject();
console.log('LoadNextAudio error: ' + error);
});
});
}
}
export default PodcastResolver;