Retrieve the audio file from the server endpoint and stream it within the Vue application

I am working on a listing module which includes an audio element for each row. I need to fetch mp3/wav files from an API and bind them correctly with the src attribute of the audio element.

Below is my code snippet:

JS
methods:{
    playa(recording_file) => {
        try {
        const requestOptions = {
            method: 'POST',
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'application/json',
                //'Authorization': 'Bearer ' + localStorage.getItem('jwt')
            },
        };      
        const response = axios.post(`api/playrecfile?rec=${recording_file}`)
        const mp3 = new Blob([response.data], { type: 'audio/mp3' })
        const url = URL.createObjectURL(mp3);//tried window.
        return url;
        } catch (e) {
          console.log('play audio error: ', e)
        }
    }
}

In the HTML (cell of a row), I can see the data and have checked the value of meta as well.

<div :class="classes" @click="click(data)" v-else-if="name=='Play'" title='Play'>
    <audio controls :ref="'audio'+data.recording_file" v-if="meta.is_admin==1 && data.recording_filename" :src="playa(data.recording_filename)">
    </audio>
    <span v-else @click="givealert()">
        <i class="fa fa-play"></i>
    </span>
</div>

PHP/Laravel

$out = isset($request->out) ? $request->out : "mp3";
header("Content-type: audio/x-$out");
header("Content-disposition: attachment; filename=tuzbd.$out");
header("Access-Control-Allow-Origin: *");
$file = base_path(). "/storage/app/recs/2019/05/03/tuzbd.mp3";
header("Content-length: " . filesize($file));
readfile($file);
return;

Answer №1

I am not familiar with the Vue-JS framework, but the logic in regular HTML5 would involve:

(1) Assign an ID to the audio tag (e.g. myAudio).

<audio id="myAudio" controls :ref="'audio'+data.recording_file" v-if="meta.is_admin==1 && data.recording_filename" :src="playa(data.recording_filename)">
</audio>

(2) Update the audio tag's source using the result of createObjectURL:
If you were to achieve this with Vue-JS, it might look something like the following:

methods:{
    playa(recording_file) => {
        try 
        {
            const requestOptions = {
                method: 'POST',
                responseType: 'arraybuffer',
                    headers:    {
                        'Content-Type': 'application/json',
                        //'Authorization': 'Bearer ' + localStorage.getItem('jwt')
                    },
            };      
            
            var response = axios.post(`api/playrecfile?rec=${recording_file}`)
            
            //# try reading into Blob as BINARY data (e.g., raw bytes)
            //const mp3 = new Blob([response.data], { type: 'audio/mp3' })
            var mp3 = new Blob([response.data], { type: 'application/octet-stream' })
            
            //const  = URL.createObjectURL(mp3);//tried window.
            //return url; //# don't Return but instead just update the audio tag's source...
            
             //# update file path for Audio tag...
            var url = (window.URL || window.webkitURL).createObjectURL( mp3 );
            
            var audioObj = document.getElementById("myAudio");
            audioObj.setAttribute("src", url); //# updates the source of the Audio tag
            
            //# If you need to handle MP3 bytes... e.g., read/modify/delete some ID3 metadata bytes...
            var reader = new FileReader();
            reader.readAsDataURL( mp3 );
            
            reader.onloadend = function(evt) 
            {
                if (evt.target.readyState == FileReader.DONE) 
                {
                    //# access MP3 bytes here... as arraybuffer
                    bytes_mp3 = new Uint8Array( evt.target.result ); //define your "var bytes_mp3" globally (var is outside of any function)
                }
            }
        } 
        catch (e) { console.log('play audio error: ', e) }
    }

The above FileReader is used to read the file as a stream of bytes (since the audio tag expects a file, meaning it is just a stream of bytes regardless of whether the data is MP3 or PDF).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...

The Impact of Ajax on Online Search Algorithms

There's a website that dynamically loads content at . An example page from the site can be found at: . The entire content on this page is generated using a cURL parser script. <?php $___notjson=1; ini_set('display_errors', 1); header (&a ...

Display every div element if none of the links have been clicked

On my webpage at url.com/yourfirstpage/, all div elements are hidden by default with a display:none property. If we specifically target #sec1 by going to url.com/yourfirstpage/#sec1, only sec1 is displayed while the others remain hidden. But what if we acc ...

I'm curious about the origin and purpose of req.user - where does it come from and

Recently, I've been delving into Nestjs and found myself a bit puzzled by the req.user. Where does this come from and do we have to manually request it? What exactly is req.user and what advantages does it offer? Must I assign payload to it manually? ...

What is the process for obtaining a value when you click and then retrieving the associated ID?

I am looking to create a function that, when clicking on the square with the ID "colors", will return the sentence containing the colors from the table in PHP files with the ID "retours_couleurs". Apologies for any mistakes in my English, as I am French. ...

Having trouble with Semantic UI Modal onShow / onVisible functionality?

Seeking assistance with resizing an embedded google map in a Semantic UI modal after it is shown. After numerous attempts, I have narrowed down the issue to receiving callbacks when the modal becomes visible. Unfortunately, the onShow or onVisible functio ...

How can I incorporate the 'client' application into the 'loading.js' file?

I implemented a Lottie component in my loading.js file. Utilizing the App router (Next13). This is the code for the lottie component: import { Player } from '@lottiefiles/react-lottie-player'; import LoadingLottie from '@/assets/loading.j ...

Leveraging the power of Notepad++

When I attempt to use Notepad++ for Javascript, it isn't functioning as expected. Instead of displaying the proper outcome on the web page, all I see is a jumbled mess. Currently, I am using version 6.6.7 of Notepad++. Here's my process: Typ ...

Tips on how to retrieve a nested promise

Within my JavaScript function, I am utilizing rest calls and the responses to construct the payload for subsequent calls. Included below is some pseudo code exemplifying my approach. Although my code is currently functional, I am unsure how to properly ret ...

Error message: "The term 'Outlet' is not recognized in react-router version 6.4"

What is the proper way to define the Outlet component in react-router version 6.4? Below is a code snippet: function Layout() { return ( <div> <Navbar /> <Outlet /> <Footer /> </div> ); } ...

Guide on dynamically importing images using the Nuxt.js and jQuery script

<template> <div> <select ref='select'> <slot></slot> </select> </div> </template> <script> import Vue from "vue" export default { name: " ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

What is the best way to restore a component's state to its default settings when it receives new props?

I have a Next.js project in development with a custom Layout already set up. I want the header component to reset whenever a new page is navigated to, so that the menu reverts back to its default state. Does anyone know how I can achieve this? import { F ...

Trouble ensues when using a scaled THREE.Sprite with THREE.Raycaster

My goal is to implement the use of THREE.Raycaster in order to display an html label whenever a user hovers over an object. The functionality works properly when using THREE.Mesh, however, with THREE.Sprite, I am noticing a strange spacing issue that seems ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Utilizing Angular 2's Routerlink with *ngIf and Parameters

Currently, I am facing an issue with a routerlink that includes a parameter: http://localhost:4200/item/1 I am trying to figure out how to implement an *ngIf statement with a parameter.... Here is what I have attempted so far: <div *ngIf="router.url ...

Can a website trigger an alarm on a user's iPhone without their permission?

Even though I have limited experience with HTML, CSS, and Javascript, I am curious if it is possible to create a basic website that can trigger an alarm on the user's device by simply clicking a button. For example, imagine a scenario where a user is ...

Utilizing key press functionality in JavaScript and jQuery

I have successfully implemented an alert box to display on a key press event. However, I am facing an issue where the alert box pops up even when typing in a textbox on the page. $(document).ready(function() { $(document).keydown(function(e) { ...

The functionality of $watch in AngularJS is not meeting the desired outcomes

Within my controller, I am looking to receive notifications when the value of a certain variable changes. Specifically, I want a function to be triggered whenever this variable is updated. To achieve this, I am utilizing the $watch method in AngularJS. Her ...

Optimize your filtering and searching experience with Vue 3 and Django Rest Framework

I'm a beginner in the world of Vue and Django, trying to create a search component for an e-commerce project that allows users to filter results as they desire. After some research, here's what I've gathered so far: Regarding the front-end ...