Skip to content

Commit 10c22f3

Browse files
committed
Merge pull request #58 from bastibe/info-function
Implement `info` function
2 parents 376c170 + 3059bda commit 10c22f3

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

soundfile.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,64 @@ def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None,
467467
yield block
468468

469469

470+
class _SoundFileInfo(object):
471+
"""Information about a SoundFile"""
472+
def __init__(self, file, verbose):
473+
self.verbose = verbose
474+
with SoundFile(file) as f:
475+
self.name = f.name
476+
self.samplerate = f.samplerate
477+
self.channels = f.channels
478+
self.duration = len(f)/f.samplerate
479+
self.format = f.format
480+
self.subtype = f.subtype
481+
self.endian = f.endian
482+
self.format_info = f.format_info
483+
self.subtype_info = f.subtype_info
484+
self.sections = f.sections
485+
self.extra_info = f.extra_info
486+
487+
@property
488+
def _duration_str(self):
489+
hours, rest = divmod(self.duration, 3600)
490+
minutes, seconds = divmod(rest, 60)
491+
if hours >= 1:
492+
duration = "{0:.0g}:{1:02.0g}:{2:05.3f} h".format(hours, minutes, seconds)
493+
elif minutes >= 1:
494+
duration = "{0:02.0g}:{1:05.3f} min".format(minutes, seconds)
495+
else:
496+
duration = "{0:.3f} s".format(seconds)
497+
return duration
498+
499+
def __repr__(self):
500+
info = "\n".join(
501+
["{0.name}",
502+
"samplerate: {0.samplerate} Hz",
503+
"channels: {0.channels}",
504+
"duration: {0._duration_str}",
505+
"format: {0.format_info} [{0.format}]",
506+
"subtype: {0.subtype_info} [{0.subtype}]"])
507+
if self.verbose:
508+
info += "\n".join(
509+
["\nendian: {0.endian}",
510+
"sections: {0.sections}",
511+
'extra_info: """',
512+
' {1}"""'])
513+
indented_extra_info = ("\n"+" "*4).join(self.extra_info.split("\n"))
514+
return info.format(self, indented_extra_info)
515+
516+
517+
def info(file, verbose=False):
518+
"""Returns an object with information about a SoundFile.
519+
520+
Parameters
521+
----------
522+
verbose : bool
523+
Whether to print additional information.
524+
"""
525+
return _SoundFileInfo(file, verbose)
526+
527+
470528
def available_formats():
471529
"""Return a dictionary of available major formats.
472530

0 commit comments

Comments
 (0)