How to convert Django bytes data to mp3 files

108 views Asked by At

I have send audid/webm bytes from react to django.

the code in view.py is like this

def get_audio(request):
    audio = BytesIO(request.body)
    print(audio.read())
    print(type(audio.read()))

    # os.makedirs('./data/audio.wav', exist_ok=True)
    # with open('./data/audio.wav', mode='bx') as f:
    #     f.write(audio.read())

    return HttpResponse("audio delievered")

the request in react is like this

setTimeout(() => {
          setRec("Stopped")
          const tracks = stream.getTracks();
          tracks[0].stop();
          mediaRecorder.stop()
          // console.log(chunks[0])
          
          blobAudio = chunks[0]
}, 5000);
const audioUpload = () => {
  const fd = new FormData();
  fd.append("audio_5sec", blobAudio);
  try{
    axios.post("/uploading_audio", fd,
      {
      headers:{
        'Content-Type' : 'multipart/form-data',
      },
    })
      .then((response) => {
        console.log(response);
      })
  }catch(error){
    console.log(error);
  }
}

now i want to convert audio.read() bytes to mp3 in django directory and write it. How can i do this? The above comment parts doesn't work

1

There are 1 answers

3
Chukwujiobi Canon On

Your code creates a directory data/audio.wav recursively and then tries to open the file audio.wav but audio.wav is a directory not a file.

Do this instead:

def get_audio(request):
    audio = BytesIO(request.body)
    os.makedirs('./data', exist_ok=True) # create a directory 'data', fail if the directory already exist.
    with open('./data/audio.wav', mode='bx') as f: # open a file object 'audio.wav', fail if the file object already exists.
        f.write(audio.read())
    return HttpResponse("audio delivered")