PuriDevelopers

Untitled

Nov 18th, 2023
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. Certainly! Here's the modified code that returns the `base64data` from the function:
  2.  
  3. ```javascript
  4. // Function to fetch audio from URL and convert it to base64
  5. async function fetchAndConvertToBase64(url) {
  6. try {
  7. const response = await fetch(url);
  8. const audioBlob = await response.blob();
  9.  
  10. const reader = new FileReader();
  11. reader.readAsDataURL(audioBlob);
  12. return new Promise((resolve, reject) => {
  13. reader.onloadend = function () {
  14. const base64data = reader.result.split(',')[1]; // Extract base64 data
  15. resolve(base64data);
  16. };
  17. });
  18. } catch (error) {
  19. console.error('Error fetching or converting audio to base64:', error);
  20. return null;
  21. }
  22. }
  23.  
  24. // Example usage:
  25. const audioURL = 'YOUR_AUDIO_URL_HERE';
  26. fetchAndConvertToBase64(audioURL)
  27. .then(base64data => {
  28. if (base64data) {
  29. // Use the base64 data here as needed
  30. console.log('Base64 data:', base64data);
  31. // Call function to play audio using Audio5js or perform other actions
  32. // playAudioUsingAudio5js(base64data);
  33. } else {
  34. console.error('No base64 data available.');
  35. }
  36. });
  37. ```
  38.  
  39. This updated function `fetchAndConvertToBase64()` now returns a Promise that resolves with the `base64data` of the fetched audio. You can use this function and handle the returned `base64data` accordingly in your application, such as playing it using Audio5js or performing any other necessary actions.
Add Comment
Please, Sign In to add comment