Weilory
Weilory

Reputation: 3101

python get audio duration from blob

my question is similar to Get .wav file length or duration.

  1. use MediaRecorder in js frontend to record audio
  2. send blob to backend

I want to apply a length limit of 30 seconds, but all I have is a blob, should be stored in django BinaryField.


the frontend blob format is in type: "audio/mp4"

since in backend I don't want to create a file in each request, I only want to access the length of the audio, I am grateful for your suggestions.

Upvotes: 1

Views: 781

Answers (2)

pxeba
pxeba

Reputation: 1766

The previous solution also gave me an error. this is the way I receive and process on my server. Works with all types of files

file = request.files.get('file')
get_audio_duration(file)
import io
import soundfile as sf

def get_audio_duration(file):
    content = file.read()
    audio_io = io.BytesIO(content)
    data, samplerate = sf.read(audio_io)
    return len(data) / samplerate

Upvotes: 1

Seon
Seon

Reputation: 3975

You want to use the io package to give your in-memory data a file-like interface for other libraries (like wave).

An example below:

from io import BytesIO

with open("sample.wav", "rb") as f:
  blob = f.read()

data = BytesIO(blob)

data can then be treated like any wav file:

import wave
import contextlib

with contextlib.closing(wave.open(data,'r')) as f:
    frames = f.getnframes()
    rate = f.getframerate()
    duration = frames / float(rate)
    print(duration)

Upvotes: 1

Related Questions