Skip to content

Commit

Permalink
Add proper modularization to soundfile backend
Browse files Browse the repository at this point in the history
  • Loading branch information
mthrok committed Jun 4, 2020
1 parent ec9d849 commit 4940d54
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions torchaudio/_soundfile_backend.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import os
from typing import Any, Optional, Tuple, Union
from typing import Any, Optional, Tuple

import torch
from torch import Tensor

from torchaudio.common_utils import check_input
from torchaudio.common_utils import (
is_module_available,
requires_module,
check_input,
)

if is_module_available('soundfile'):
import soundfile


_subtype_to_precision = {
Expand Down Expand Up @@ -46,6 +53,7 @@ def __init__(self,
self.opposite_endian = opposite_endian


@requires_module('soundfile')
def load(filepath: str,
out: Optional[Tensor] = None,
normalization: Optional[bool] = True,
Expand Down Expand Up @@ -76,8 +84,6 @@ def load(filepath: str,
if offset < 0:
raise ValueError("Expected positive offset value")

import soundfile

# initialize output tensor
# TODO call libsoundfile directly to avoid numpy
out, sample_rate = soundfile.read(
Expand All @@ -94,6 +100,7 @@ def load(filepath: str,
return out, sample_rate


@requires_module('soundfile')
def save(filepath: str, src: Tensor, sample_rate: int, precision: int = 16, channels_first: bool = True) -> None:
r"""See torchaudio.save"""

Expand Down Expand Up @@ -123,14 +130,13 @@ def save(filepath: str, src: Tensor, sample_rate: int, precision: int = 16, chan

precision = "PCM_S8" if precision == 8 else "PCM_" + str(precision)

import soundfile
return soundfile.write(filepath, src, sample_rate, precision)


@requires_module('soundfile')
def info(filepath: str) -> Tuple[SignalInfo, EncodingInfo]:
r"""See torchaudio.info"""

import soundfile
sfi = soundfile.info(filepath)

precision = _subtype_to_precision[sfi.subtype]
Expand Down

0 comments on commit 4940d54

Please sign in to comment.