Determine type of sound file using Python (sndhdr)


The sndhdr module in Python's standard library provides utility functions that read the type of sound data which is in a file. The functions return a namedtuple(), containing five attributes

filetypestring representing 'aifc', 'aiff', 'au', 'hcom', 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul'.
frameratethe sampling_rate will be either the actual value or 0 if unknown or difficult to decode.
nchannelsnumber of channels or 0 if it cannot be determined or if the value is difficult to decode
nframeseither the number of frames or -1.
sampwidthbits_per_sample, will either be the sample size in bits or 'A' for A-LAW or 'U' for u-LAW.

functions in sndhdr module

sndhdr.what()

This function determines the type of sound data stored in the file filename using whathdr(). If it succeeds, returns a namedtuple as described above, otherwise None is returned.

sndhdr.whathdr()

This function determines the type of sound data stored in a file based on the file header. This function returns a namedtuple as described above on success, or None.

Examples

>>> import sndhdr
>>> sndhdr.whathdr("sample.wav")
SndHeaders(filetype = 'wav', framerate = 44100, nchannels = 1, nframes = 99999, sampwidth = 16)
>>> sndhdr.whathdr("sample.aiff")
SndHeaders(filetype = 'aiff', framerate = 8000, nchannels = 1, nframes = 271200, sampwidth = 16)
>>> sndhdr.whathdr("sample.au")
SndHeaders(filetype = 'au', framerate = 8000, nchannels = 1, nframes = 103397.0, sampwidth = 'U')

Updated on: 30-Jun-2020

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements