Skip to content

Commit

Permalink
Add warning for non-integer resampling frequencies (pytorch#1490)
Browse files Browse the repository at this point in the history
  • Loading branch information
Caroline Chen committed May 12, 2021
1 parent ffd2f0a commit 0ab30b3
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
27 changes: 26 additions & 1 deletion test/torchaudio_unittest/functional/functional_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from parameterized import parameterized
from scipy import signal

from torchaudio_unittest.common_utils import TestBaseMixin, get_sinusoid, nested_params
from torchaudio_unittest.common_utils import TestBaseMixin, get_sinusoid, nested_params, get_whitenoise


class Functional(TestBaseMixin):
Expand Down Expand Up @@ -259,6 +259,31 @@ def test_mask_along_axis_iid_preserve(self, mask_param, mask_value, axis):

self.assertEqual(specgrams, specgrams_copy)

def test_resample_no_warning(self):
sample_rate = 44100
waveform = get_whitenoise(sample_rate=sample_rate, duration=0.1)

with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
F.resample(waveform, float(sample_rate), sample_rate / 2.)
assert len(w) == 0

def test_resample_warning(self):
"""resample should throw a warning if an input frequency is not of an integer value"""
sample_rate = 44100
waveform = get_whitenoise(sample_rate=sample_rate, duration=0.1)

with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
F.resample(waveform, sample_rate, 5512.5)
assert len(w) == 1


class FunctionalComplex(TestBaseMixin):
complex_dtype = None
real_dtype = None
device = None

@nested_params(
[0.5, 1.01, 1.3],
[True, False],
Expand Down
13 changes: 13 additions & 0 deletions torchaudio/functional/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,19 @@ def resample(

assert orig_freq > 0.0 and new_freq > 0.0

if not (int(orig_freq) == orig_freq and int(new_freq) == new_freq):
warnings.warn(
"Non-integer frequencies are being cast to ints and may result in poor resampling quality "
"because the underlying algorithm requires an integer ratio between `orig_freq` and `new_freq`. "
"Using non-integer valued frequencies will throw an error in the next release. "
"To work around this issue, manually convert both frequencies to integer values "
"that maintain their resampling rate ratio before passing them into the function "
"Example: To downsample a 44100 hz waveform by a factor of 8, use "
"`orig_freq=8` and `new_freq=1` instead of `orig_freq=44100` and `new_freq=5512.5` "
"For more information or to leave feedback about this change, please refer to "
"https://github.com/pytorch/audio/issues/1487."
)

orig_freq = int(orig_freq)
new_freq = int(new_freq)
gcd = math.gcd(orig_freq, new_freq)
Expand Down

0 comments on commit 0ab30b3

Please sign in to comment.