Question:
Sending Audio file from Django to Vue

Problem:

I'm trying to send gtts generated audio file from Django to Vue via HttpResponse.

Django's views.py:

f = open('path/of/mp3/file', 'rb')

response = HttpResponse()

response.write(f.read())

response['Content-Type'] = 'audio/mp3'

response['Content-Length'] = os.path.getsize('path/of/mp3/file')


return response



and when vue receives the response data, it is like the below:

data: '��D�\x00\x11C\x19�\x01F(\x00\x00\x04 �&N�""""���ޓ�������\x7F���B\x10���w�����…���_�F��1B��H���\x16LAME3.100�����������������������' # and so on




I guess it is because the bytes have been converted to string over the transfer and I have to convert it back to the audio file. But no matter whether using blob or other suggested methods, I could not convert it to an mp3 file to be played in javascript.


How could I achieve this?


Solution:

There are multiple ways to play audio in the browser, so it really depends on how you mean to play your audio file.


creating <audio> element


const el = document.createElement('audio');

el.src = `${API_URL}/file.mp3`;

el.play();


using Audio() constructor


new Audio(`${API_URL}/file.mp3`).play();


converting binary data (Axios)


const context = new AudioContext();


axios

  .get(`${API_URL}/file.mp3`, {

    responseType: 'arraybuffer'

  })

  .then(res => {

    context.decodeAudioData(res.data).then(buffer => {

      const source = context.createBufferSource();

      source.buffer = buffer;

      source.connect(context.destination);

      source.start();

    });

  });


converting binary data (Fetch API)


const context = new AudioContext();


fetch(`${API_URL}/file.mp3`).then(res => {

  res.arrayBuffer().then(arrayBuffer => {

    context.decodeAudioData(arrayBuffer).then(buffer => {

      const source = context.createBufferSource();

      source.buffer = buffer;

      source.connect(context.destination);

      source.start();

    });

  });

});



Hopefully one of these methods helps.


Suggested blogs:

>How to solve the issue of producing the wrong output value in PHP?

>How to solve XGBoost model training fails in Python

>How to Upload files and JSON data in the same request with Angular?

>How to fix when Postgres connection refused while running laravel tests on gitlab CI?

>Changing main page as Identity's Login page in ASP.NET Core 7

>How can I get the original type of a Mock after the Mock has been cast to an object


Ritu Singh

Ritu Singh

Submit
0 Answers