Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new_util/get_sound_duration #254

Merged
merged 1 commit into from
Jun 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions ovos_utils/sound.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import os
import subprocess
import wave
from copy import deepcopy
from os.path import isfile
from typing import Optional

from distutils.spawn import find_executable

from ovos_utils.log import LOG
Expand Down Expand Up @@ -115,3 +119,36 @@ def play_audio(uri, play_cmd=None, environment=None):
LOG.error(f"Failed to play: {play_cmd}")
LOG.exception(e)
return None


def get_sound_duration(path: str, base_dir: Optional[str] = "") -> float:
"""return sound duration, in seconds"""
if base_dir and path.startswith("snd/"):
resolved_path = f"{base_dir}/{path}"
if isfile(resolved_path):
path = resolved_path

if not isfile(path):
raise FileNotFoundError(f"could not resolve sound file: {path}")

if path.endswith(".wav"):
with wave.open(path, 'r') as f:
frames = f.getnframes()
rate = f.getframerate()
return frames / float(rate)
media_info = find_executable("mediainfo")
if media_info:
args = (media_info, path)
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read().decode("utf-8").split("Duration")[1].split("\n")[0]
output = "".join([c for c in output if c.isdigit()])
return int(output) / 1000
ffprobe = find_executable("ffprobe")
if ffprobe:
args = (ffprobe, "-show_entries", "format=duration", "-i", path)
popen = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
popen.wait()
output = popen.stdout.read().decode("utf-8")
return float(output.split("duration=")[-1].split("\n")[0])
raise RuntimeError("Failed to determine sound length, please install mediainfo or ffprobe")
Loading