PuriDevelopers

Untitled

Nov 18th, 2023
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. To convert audio from a URL to base64 and then play it using Audio5js in JavaScript, you can follow these steps:
  2.  
  3. 1. Fetch the audio file from the URL.
  4. 2. Convert the fetched audio to a base64 string.
  5. 3. Use Audio5js to create an audio element and play the base64-encoded audio.
  6.  
  7. Here's a basic example using JavaScript:
  8.  
  9. ```javascript
  10. // Function to fetch audio from URL and convert it to base64
  11. async function fetchAndPlayAudio(url) {
  12. try {
  13. const response = await fetch(url);
  14. const audioBlob = await response.blob();
  15.  
  16. const reader = new FileReader();
  17. reader.readAsDataURL(audioBlob);
  18. reader.onloadend = function () {
  19. const base64data = reader.result.split(',')[1]; // Extract base64 data
  20. playAudioUsingAudio5js(base64data);
  21. };
  22. } catch (error) {
  23. console.error('Error fetching or playing audio:', error);
  24. }
  25. }
  26.  
  27. // Function to play audio using Audio5js
  28. function playAudioUsingAudio5js(base64data) {
  29. var audio = new Audio5js({
  30. formats: ['mp3', 'ogg', 'wav'],
  31. autoplay: true,
  32. loop: false,
  33. ready: function () {
  34. this.load('data:audio/mp3;base64,' + base64data); // Change mime type accordingly
  35. this.play();
  36. }
  37. });
  38. }
  39.  
  40. // Example usage:
  41. const audioURL = 'YOUR_AUDIO_URL_HERE';
  42. fetchAndPlayAudio(audioURL);
  43. ```
  44.  
  45. Replace `'YOUR_AUDIO_URL_HERE'` with the actual URL of the audio file you want to play. This code fetches the audio file from the given URL, converts it to base64, and then uses Audio5js to play the audio using the generated base64 data.
  46.  
  47. Remember, this is a simplified example. Depending on the browser's security policies, you might face restrictions when attempting to fetch audio from some URLs due to CORS (Cross-Origin Resource Sharing) policies.
Add Comment
Please, Sign In to add comment