Python Sndhdr Module
The sndhdr module provides utility functions which attempt to determine the type of sound data which is in a file.
Note: The sndhdr module is deprecated as of Python 3.11 and was removed in Python 3.13. It is recommended to use external libraries like filetype, puremagic, or python-magic for file type detection.
Importing the Module
import sndhdr
Determining Sound File Type
sndhdr.what()
The sndhdr.what() function determines the type of sound data stored in the file filename.
import sndhdr
filename = 'sample.wav'
# Returns a named tuple: (filetype, framerate, nchannels, nframes, sampwidth)
# or None if the type cannot be determined.
info = sndhdr.what(filename)
if info:
print(f"File type: {info.filetype}")
print(f"Frame rate: {info.framerate}")
print(f"Channels: {info.nchannels}")
print(f"Frames: {info.nframes}")
print(f"Sample width: {info.sampwidth}")
else:
print("Could not determine sound file type.")
sndhdr.whathdr()
The sndhdr.whathdr() function determines the type of sound data stored in a file based on the file header.
import sndhdr
info = sndhdr.whathdr('sample.aiff')
print(info)
Return Values
The functions return a named tuple containing:
filetype: The type of the sound file (e.g., 'aiff', 'au', 'hcom', 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul').framerate: The sampling rate.nchannels: The number of channels.nframes: The number of frames (or -1 if unknown).sampwidth: The sample width in bits (e.g., 'A' for A-LAW, 'U' for u-LAW).