|
| 1 | +from pathlib import Path |
| 2 | +from typing import Optional, Union |
| 3 | + |
| 4 | +import torch |
| 5 | +from torch import Tensor |
| 6 | + |
| 7 | +from torchcodec import _core |
| 8 | + |
| 9 | + |
| 10 | +class AudioEncoder: |
| 11 | + def __init__(self, samples: Tensor, *, sample_rate: int): |
| 12 | + # Some of these checks are also done in C++: it's OK, they're cheap, and |
| 13 | + # doing them here allows to surface them when the AudioEncoder is |
| 14 | + # instantiated, rather than later when the encoding methods are called. |
| 15 | + if not isinstance(samples, Tensor): |
| 16 | + raise ValueError( |
| 17 | + f"Expected samples to be a Tensor, got {type(samples) = }." |
| 18 | + ) |
| 19 | + if samples.ndim != 2: |
| 20 | + raise ValueError(f"Expected 2D samples, got {samples.shape = }.") |
| 21 | + if samples.dtype != torch.float32: |
| 22 | + raise ValueError(f"Expected float32 samples, got {samples.dtype = }.") |
| 23 | + if sample_rate <= 0: |
| 24 | + raise ValueError(f"{sample_rate = } must be > 0.") |
| 25 | + |
| 26 | + self._samples = samples |
| 27 | + self._sample_rate = sample_rate |
| 28 | + |
| 29 | + def to_file( |
| 30 | + self, |
| 31 | + dest: Union[str, Path], |
| 32 | + *, |
| 33 | + bit_rate: Optional[int] = None, |
| 34 | + ) -> None: |
| 35 | + _core.encode_audio_to_file( |
| 36 | + wf=self._samples, |
| 37 | + sample_rate=self._sample_rate, |
| 38 | + filename=dest, |
| 39 | + bit_rate=bit_rate, |
| 40 | + ) |
| 41 | + |
| 42 | + def to_tensor( |
| 43 | + self, |
| 44 | + format: str, |
| 45 | + *, |
| 46 | + bit_rate: Optional[int] = None, |
| 47 | + ) -> Tensor: |
| 48 | + return _core.encode_audio_to_tensor( |
| 49 | + wf=self._samples, |
| 50 | + sample_rate=self._sample_rate, |
| 51 | + format=format, |
| 52 | + bit_rate=bit_rate, |
| 53 | + ) |
0 commit comments