We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Save signal with AMR-NB format
Conversion with `sox input.wav -r 8k ouptut.amr-nb` command works fine, `libsox-fmt-all` is installed.

```python
# saving to GSM works:
torchaudio.save('output.gsm', signal, 8000)

# saving to AMR-NB does not:
torchaudio.save('output.amr-nb', signal, 8000)
#formats: no handler for given file type `amr-nb'
#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#  File "/miniconda/lib/python3.7/site-packages/torchaudio/__init__.py", line 133, in save
#    return save_encinfo(filepath, src, channels_first, si)
#  File "/miniconda/lib/python3.7/site-packages/torchaudio/__init__.py", line 202, in save_encinfo
#    _torch_sox.write_audio_file(filepath, src, signalinfo, encodinginfo, filetype)
#RuntimeError: Error writing audio file: could not open file for writing
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `build_tools/setup_helpers/extension.py`
Content:
```
1 import os
2 import platform
3 import subprocess
4 from pathlib import Path
5 
6 from torch.utils.cpp_extension import (
7     CppExtension,
8     BuildExtension as TorchBuildExtension
9 )
10 
11 __all__ = [
12     'get_ext_modules',
13     'BuildExtension',
14 ]
15 
16 _THIS_DIR = Path(__file__).parent.resolve()
17 _ROOT_DIR = _THIS_DIR.parent.parent.resolve()
18 _CSRC_DIR = _ROOT_DIR / 'torchaudio' / 'csrc'
19 _TP_BASE_DIR = _ROOT_DIR / 'third_party'
20 _TP_INSTALL_DIR = _TP_BASE_DIR / 'install'
21 
22 
23 def _get_build_sox():
24     val = os.environ.get('BUILD_SOX', '0')
25     trues = ['1', 'true', 'TRUE', 'on', 'ON', 'yes', 'YES']
26     falses = ['0', 'false', 'FALSE', 'off', 'OFF', 'no', 'NO']
27     if val in trues:
28         return True
29     if val not in falses:
30         print(
31             f'WARNING: Unexpected environment variable value `BUILD_SOX={val}`. '
32             f'Expected one of {trues + falses}')
33     return False
34 
35 
36 _BUILD_SOX = _get_build_sox()
37 
38 
39 def _get_eca(debug):
40     eca = []
41     if debug:
42         eca += ["-O0", "-g"]
43     else:
44         eca += ["-O3"]
45     return eca
46 
47 
48 def _get_ela(debug):
49     ela = []
50     if debug:
51         if platform.system() == "Windows":
52             ela += ["/DEBUG:FULL"]
53         else:
54             ela += ["-O0", "-g"]
55     else:
56         ela += ["-O3"]
57     return ela
58 
59 
60 def _get_srcs():
61     return [str(p) for p in _CSRC_DIR.glob('**/*.cpp')]
62 
63 
64 def _get_include_dirs():
65     dirs = [
66         str(_ROOT_DIR),
67     ]
68     if _BUILD_SOX:
69         dirs.append(str(_TP_INSTALL_DIR / 'include'))
70     return dirs
71 
72 
73 def _get_extra_objects():
74     objs = []
75     if _BUILD_SOX:
76         # NOTE: The order of the library listed bellow matters.
77         #
78         # (the most important thing is that dependencies come after a library
79         # e.g., sox comes first, flac/vorbis comes before ogg, and
80         # vorbisenc/vorbisfile comes before vorbis
81         libs = [
82             'libsox.a',
83             'libmad.a',
84             'libFLAC.a',
85             'libmp3lame.a',
86             'libopusfile.a',
87             'libopus.a',
88             'libvorbisenc.a',
89             'libvorbisfile.a',
90             'libvorbis.a',
91             'libogg.a',
92         ]
93         for lib in libs:
94             objs.append(str(_TP_INSTALL_DIR / 'lib' / lib))
95     return objs
96 
97 
98 def _get_libraries():
99     return [] if _BUILD_SOX else ['sox']
100 
101 
102 def _build_third_party():
103     build_dir = str(_TP_BASE_DIR / 'build')
104     os.makedirs(build_dir, exist_ok=True)
105     subprocess.run(
106         args=['cmake', '..'],
107         cwd=build_dir,
108         check=True,
109     )
110     subprocess.run(
111         args=['cmake', '--build', '.'],
112         cwd=build_dir,
113         check=True,
114     )
115 
116 
117 _EXT_NAME = 'torchaudio._torchaudio'
118 
119 
120 def get_ext_modules(debug=False):
121     if platform.system() == 'Windows':
122         return None
123     return [
124         CppExtension(
125             _EXT_NAME,
126             _get_srcs(),
127             libraries=_get_libraries(),
128             include_dirs=_get_include_dirs(),
129             extra_compile_args=_get_eca(debug),
130             extra_objects=_get_extra_objects(),
131             extra_link_args=_get_ela(debug),
132         ),
133     ]
134 
135 
136 class BuildExtension(TorchBuildExtension):
137     def build_extension(self, ext):
138         if ext.name == _EXT_NAME and _BUILD_SOX:
139             _build_third_party()
140         super().build_extension(ext)
141
```

Path: `torchaudio/backend/sox_io_backend.py`
Content:
```
1 from typing import Tuple, Optional
2 
3 import torch
4 from torchaudio._internal import (
5     module_utils as _mod_utils,
6 )
7 
8 from .common import AudioMetaData
9 
10 
11 @_mod_utils.requires_module('torchaudio._torchaudio')
12 def info(filepath: str) -> AudioMetaData:
13     """Get signal information of an audio file.
14 
15     Args:
16         filepath (str or pathlib.Path):
17             Path to audio file. This function also handles ``pathlib.Path`` objects,
18             but is annotated as ``str`` for TorchScript compatibility.
19 
20     Returns:
21         AudioMetaData: Metadata of the given audio.
22     """
23     # Cast to str in case type is `pathlib.Path`
24     filepath = str(filepath)
25     sinfo = torch.ops.torchaudio.sox_io_get_info(filepath)
26     return AudioMetaData(sinfo.get_sample_rate(), sinfo.get_num_frames(), sinfo.get_num_channels())
27 
28 
29 @_mod_utils.requires_module('torchaudio._torchaudio')
30 def load(
31         filepath: str,
32         frame_offset: int = 0,
33         num_frames: int = -1,
34         normalize: bool = True,
35         channels_first: bool = True,
36 ) -> Tuple[torch.Tensor, int]:
37     """Load audio data from file.
38 
39     Note:
40         This function can handle all the codecs that underlying libsox can handle,
41         however it is tested on the following formats;
42 
43         * WAV
44 
45             * 32-bit floating-point
46             * 32-bit signed integer
47             * 16-bit signed integer
48             * 8-bit unsigned integer
49 
50         * MP3
51         * FLAC
52         * OGG/VORBIS
53         * OPUS
54         * SPHERE
55 
56         To load ``MP3``, ``FLAC``, ``OGG/VORBIS``, ``OPUS`` and other codecs ``libsox`` does not
57         handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``
58         and corresponding codec libraries such as ``libmad`` or ``libmp3lame`` etc.
59 
60     By default (``normalize=True``, ``channels_first=True``), this function returns Tensor with
61     ``float32`` dtype and the shape of ``[channel, time]``.
62     The samples are normalized to fit in the range of ``[-1.0, 1.0]``.
63 
64     When the input format is WAV with integer type, such as 32-bit signed integer, 16-bit
65     signed integer and 8-bit unsigned integer (24-bit signed integer is not supported),
66     by providing ``normalize=False``, this function can return integer Tensor, where the samples
67     are expressed within the whole range of the corresponding dtype, that is, ``int32`` tensor
68     for 32-bit signed PCM, ``int16`` for 16-bit signed PCM and ``uint8`` for 8-bit unsigned PCM.
69 
70     ``normalize`` parameter has no effect on 32-bit floating-point WAV and other formats, such as
71     ``flac`` and ``mp3``.
72     For these formats, this function always returns ``float32`` Tensor with values normalized to
73     ``[-1.0, 1.0]``.
74 
75     Args:
76         filepath (str or pathlib.Path):
77             Path to audio file. This function also handles ``pathlib.Path`` objects, but is
78             annotated as ``str`` for TorchScript compiler compatibility.
79         frame_offset (int):
80             Number of frames to skip before start reading data.
81         num_frames (int):
82             Maximum number of frames to read. ``-1`` reads all the remaining samples,
83             starting from ``frame_offset``.
84             This function may return the less number of frames if there is not enough
85             frames in the given file.
86         normalize (bool):
87             When ``True``, this function always return ``float32``, and sample values are
88             normalized to ``[-1.0, 1.0]``.
89             If input file is integer WAV, giving ``False`` will change the resulting Tensor type to
90             integer type.
91             This argument has no effect for formats other than integer WAV type.
92         channels_first (bool):
93             When True, the returned Tensor has dimension ``[channel, time]``.
94             Otherwise, the returned Tensor's dimension is ``[time, channel]``.
95 
96     Returns:
97         torch.Tensor:
98             If the input file has integer wav format and normalization is off, then it has
99             integer type, else ``float32`` type. If ``channels_first=True``, it has
100             ``[channel, time]`` else ``[time, channel]``.
101     """
102     # Cast to str in case type is `pathlib.Path`
103     filepath = str(filepath)
104     signal = torch.ops.torchaudio.sox_io_load_audio_file(
105         filepath, frame_offset, num_frames, normalize, channels_first)
106     return signal.get_tensor(), signal.get_sample_rate()
107 
108 
109 @_mod_utils.requires_module('torchaudio._torchaudio')
110 def save(
111         filepath: str,
112         src: torch.Tensor,
113         sample_rate: int,
114         channels_first: bool = True,
115         compression: Optional[float] = None,
116 ):
117     """Save audio data to file.
118 
119     Note:
120         Supported formats are;
121 
122         * WAV
123 
124             * 32-bit floating-point
125             * 32-bit signed integer
126             * 16-bit signed integer
127             * 8-bit unsigned integer
128 
129         * MP3
130         * FLAC
131         * OGG/VORBIS
132         * SPHERE
133 
134         To save ``MP3``, ``FLAC``, ``OGG/VORBIS``, and other codecs ``libsox`` does not
135         handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``
136         and corresponding codec libraries such as ``libmad`` or ``libmp3lame`` etc.
137 
138     Args:
139         filepath (str or pathlib.Path):
140             Path to save file. This function also handles ``pathlib.Path`` objects, but is annotated
141             as ``str`` for TorchScript compiler compatibility.
142         tensor (torch.Tensor): Audio data to save. must be 2D tensor.
143         sample_rate (int): sampling rate
144         channels_first (bool):
145             If ``True``, the given tensor is interpreted as ``[channel, time]``,
146             otherwise ``[time, channel]``.
147         compression (Optional[float]):
148             Used for formats other than WAV. This corresponds to ``-C`` option of ``sox`` command.
149 
150                 * | ``MP3``: Either bitrate (in ``kbps``) with quality factor, such as ``128.2``, or
151                   | VBR encoding with quality factor such as ``-4.2``. Default: ``-4.5``.
152                 * | ``FLAC``: compression level. Whole number from ``0`` to ``8``.
153                   | ``8`` is default and highest compression.
154                 * | ``OGG/VORBIS``: number from ``-1`` to ``10``; ``-1`` is the highest compression
155                   | and lowest quality. Default: ``3``.
156 
157             See the detail at http://sox.sourceforge.net/soxformat.html.
158     """
159     # Cast to str in case type is `pathlib.Path`
160     filepath = str(filepath)
161     if compression is None:
162         ext = str(filepath).split('.')[-1].lower()
163         if ext in ['wav', 'sph']:
164             compression = 0.
165         elif ext == 'mp3':
166             compression = -4.5
167         elif ext == 'flac':
168             compression = 8.
169         elif ext in ['ogg', 'vorbis']:
170             compression = 3.
171         else:
172             raise RuntimeError(f'Unsupported file type: "{ext}"')
173     signal = torch.classes.torchaudio.TensorSignal(src, sample_rate, channels_first)
174     torch.ops.torchaudio.sox_io_save_audio_file(filepath, signal, compression)
175 
176 
177 @_mod_utils.requires_module('torchaudio._torchaudio')
178 @_mod_utils.deprecated('Please use "torchaudio.load".', '0.9.0')
179 def load_wav(
180         filepath: str,
181         frame_offset: int = 0,
182         num_frames: int = -1,
183         channels_first: bool = True,
184 ) -> Tuple[torch.Tensor, int]:
185     """Load wave file.
186 
187     This function is defined only for the purpose of compatibility against other backend
188     for simple usecases, such as ``torchaudio.load_wav(filepath)``.
189     The implementation is same as :py:func:`load`.
190     """
191     return load(filepath, frame_offset, num_frames, normalize=False, channels_first=channels_first)
192
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/build_tools/setup_helpers/extension.py b/build_tools/setup_helpers/extension.py
--- a/build_tools/setup_helpers/extension.py
+++ b/build_tools/setup_helpers/extension.py
@@ -89,6 +89,8 @@
             'libvorbisfile.a',
             'libvorbis.a',
             'libogg.a',
+            'libopencore-amrnb.a',
+            'libopencore-amrwb.a',
         ]
         for lib in libs:
             objs.append(str(_TP_INSTALL_DIR / 'lib' / lib))
diff --git a/torchaudio/backend/sox_io_backend.py b/torchaudio/backend/sox_io_backend.py
--- a/torchaudio/backend/sox_io_backend.py
+++ b/torchaudio/backend/sox_io_backend.py
@@ -40,18 +40,19 @@
         This function can handle all the codecs that underlying libsox can handle,
         however it is tested on the following formats;
 
-        * WAV
+        * WAV, AMB
 
             * 32-bit floating-point
             * 32-bit signed integer
             * 16-bit signed integer
-            * 8-bit unsigned integer
+            * 8-bit unsigned integer (WAV only)
 
         * MP3
         * FLAC
         * OGG/VORBIS
         * OPUS
         * SPHERE
+        * AMR-NB
 
         To load ``MP3``, ``FLAC``, ``OGG/VORBIS``, ``OPUS`` and other codecs ``libsox`` does not
         handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``
@@ -119,7 +120,7 @@
     Note:
         Supported formats are;
 
-        * WAV
+        * WAV, AMB
 
             * 32-bit floating-point
             * 32-bit signed integer
@@ -130,6 +131,7 @@
         * FLAC
         * OGG/VORBIS
         * SPHERE
+        * AMR-NB
 
         To save ``MP3``, ``FLAC``, ``OGG/VORBIS``, and other codecs ``libsox`` does not
         handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``
@@ -160,7 +162,7 @@
     filepath = str(filepath)
     if compression is None:
         ext = str(filepath).split('.')[-1].lower()
-        if ext in ['wav', 'sph']:
+        if ext in ['wav', 'sph', 'amb', 'amr-nb']:
             compression = 0.
         elif ext == 'mp3':
             compression = -4.5

{"golden_diff": "diff --git a/build_tools/setup_helpers/extension.py b/build_tools/setup_helpers/extension.py\n--- a/build_tools/setup_helpers/extension.py\n+++ b/build_tools/setup_helpers/extension.py\n@@ -89,6 +89,8 @@\n             'libvorbisfile.a',\n             'libvorbis.a',\n             'libogg.a',\n+            'libopencore-amrnb.a',\n+            'libopencore-amrwb.a',\n         ]\n         for lib in libs:\n             objs.append(str(_TP_INSTALL_DIR / 'lib' / lib))\ndiff --git a/torchaudio/backend/sox_io_backend.py b/torchaudio/backend/sox_io_backend.py\n--- a/torchaudio/backend/sox_io_backend.py\n+++ b/torchaudio/backend/sox_io_backend.py\n@@ -40,18 +40,19 @@\n         This function can handle all the codecs that underlying libsox can handle,\n         however it is tested on the following formats;\n \n-        * WAV\n+        * WAV, AMB\n \n             * 32-bit floating-point\n             * 32-bit signed integer\n             * 16-bit signed integer\n-            * 8-bit unsigned integer\n+            * 8-bit unsigned integer (WAV only)\n \n         * MP3\n         * FLAC\n         * OGG/VORBIS\n         * OPUS\n         * SPHERE\n+        * AMR-NB\n \n         To load ``MP3``, ``FLAC``, ``OGG/VORBIS``, ``OPUS`` and other codecs ``libsox`` does not\n         handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``\n@@ -119,7 +120,7 @@\n     Note:\n         Supported formats are;\n \n-        * WAV\n+        * WAV, AMB\n \n             * 32-bit floating-point\n             * 32-bit signed integer\n@@ -130,6 +131,7 @@\n         * FLAC\n         * OGG/VORBIS\n         * SPHERE\n+        * AMR-NB\n \n         To save ``MP3``, ``FLAC``, ``OGG/VORBIS``, and other codecs ``libsox`` does not\n         handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``\n@@ -160,7 +162,7 @@\n     filepath = str(filepath)\n     if compression is None:\n         ext = str(filepath).split('.')[-1].lower()\n-        if ext in ['wav', 'sph']:\n+        if ext in ['wav', 'sph', 'amb', 'amr-nb']:\n             compression = 0.\n         elif ext == 'mp3':\n             compression = -4.5\n", "issue": "Save signal with AMR-NB format\nConversion with `sox input.wav -r 8k ouptut.amr-nb` command works fine, `libsox-fmt-all` is installed.\r\n\r\n```python\r\n# saving to GSM works:\r\ntorchaudio.save('output.gsm', signal, 8000)\r\n\r\n# saving to AMR-NB does not:\r\ntorchaudio.save('output.amr-nb', signal, 8000)\r\n#formats: no handler for given file type `amr-nb'\r\n#Traceback (most recent call last):\r\n#  File \"<stdin>\", line 1, in <module>\r\n#  File \"/miniconda/lib/python3.7/site-packages/torchaudio/__init__.py\", line 133, in save\r\n#    return save_encinfo(filepath, src, channels_first, si)\r\n#  File \"/miniconda/lib/python3.7/site-packages/torchaudio/__init__.py\", line 202, in save_encinfo\r\n#    _torch_sox.write_audio_file(filepath, src, signalinfo, encodinginfo, filetype)\r\n#RuntimeError: Error writing audio file: could not open file for writing\r\n```\n", "before_files": [{"content": "import os\nimport platform\nimport subprocess\nfrom pathlib import Path\n\nfrom torch.utils.cpp_extension import (\n    CppExtension,\n    BuildExtension as TorchBuildExtension\n)\n\n__all__ = [\n    'get_ext_modules',\n    'BuildExtension',\n]\n\n_THIS_DIR = Path(__file__).parent.resolve()\n_ROOT_DIR = _THIS_DIR.parent.parent.resolve()\n_CSRC_DIR = _ROOT_DIR / 'torchaudio' / 'csrc'\n_TP_BASE_DIR = _ROOT_DIR / 'third_party'\n_TP_INSTALL_DIR = _TP_BASE_DIR / 'install'\n\n\ndef _get_build_sox():\n    val = os.environ.get('BUILD_SOX', '0')\n    trues = ['1', 'true', 'TRUE', 'on', 'ON', 'yes', 'YES']\n    falses = ['0', 'false', 'FALSE', 'off', 'OFF', 'no', 'NO']\n    if val in trues:\n        return True\n    if val not in falses:\n        print(\n            f'WARNING: Unexpected environment variable value `BUILD_SOX={val}`. '\n            f'Expected one of {trues + falses}')\n    return False\n\n\n_BUILD_SOX = _get_build_sox()\n\n\ndef _get_eca(debug):\n    eca = []\n    if debug:\n        eca += [\"-O0\", \"-g\"]\n    else:\n        eca += [\"-O3\"]\n    return eca\n\n\ndef _get_ela(debug):\n    ela = []\n    if debug:\n        if platform.system() == \"Windows\":\n            ela += [\"/DEBUG:FULL\"]\n        else:\n            ela += [\"-O0\", \"-g\"]\n    else:\n        ela += [\"-O3\"]\n    return ela\n\n\ndef _get_srcs():\n    return [str(p) for p in _CSRC_DIR.glob('**/*.cpp')]\n\n\ndef _get_include_dirs():\n    dirs = [\n        str(_ROOT_DIR),\n    ]\n    if _BUILD_SOX:\n        dirs.append(str(_TP_INSTALL_DIR / 'include'))\n    return dirs\n\n\ndef _get_extra_objects():\n    objs = []\n    if _BUILD_SOX:\n        # NOTE: The order of the library listed bellow matters.\n        #\n        # (the most important thing is that dependencies come after a library\n        # e.g., sox comes first, flac/vorbis comes before ogg, and\n        # vorbisenc/vorbisfile comes before vorbis\n        libs = [\n            'libsox.a',\n            'libmad.a',\n            'libFLAC.a',\n            'libmp3lame.a',\n            'libopusfile.a',\n            'libopus.a',\n            'libvorbisenc.a',\n            'libvorbisfile.a',\n            'libvorbis.a',\n            'libogg.a',\n        ]\n        for lib in libs:\n            objs.append(str(_TP_INSTALL_DIR / 'lib' / lib))\n    return objs\n\n\ndef _get_libraries():\n    return [] if _BUILD_SOX else ['sox']\n\n\ndef _build_third_party():\n    build_dir = str(_TP_BASE_DIR / 'build')\n    os.makedirs(build_dir, exist_ok=True)\n    subprocess.run(\n        args=['cmake', '..'],\n        cwd=build_dir,\n        check=True,\n    )\n    subprocess.run(\n        args=['cmake', '--build', '.'],\n        cwd=build_dir,\n        check=True,\n    )\n\n\n_EXT_NAME = 'torchaudio._torchaudio'\n\n\ndef get_ext_modules(debug=False):\n    if platform.system() == 'Windows':\n        return None\n    return [\n        CppExtension(\n            _EXT_NAME,\n            _get_srcs(),\n            libraries=_get_libraries(),\n            include_dirs=_get_include_dirs(),\n            extra_compile_args=_get_eca(debug),\n            extra_objects=_get_extra_objects(),\n            extra_link_args=_get_ela(debug),\n        ),\n    ]\n\n\nclass BuildExtension(TorchBuildExtension):\n    def build_extension(self, ext):\n        if ext.name == _EXT_NAME and _BUILD_SOX:\n            _build_third_party()\n        super().build_extension(ext)\n", "path": "build_tools/setup_helpers/extension.py"}, {"content": "from typing import Tuple, Optional\n\nimport torch\nfrom torchaudio._internal import (\n    module_utils as _mod_utils,\n)\n\nfrom .common import AudioMetaData\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\ndef info(filepath: str) -> AudioMetaData:\n    \"\"\"Get signal information of an audio file.\n\n    Args:\n        filepath (str or pathlib.Path):\n            Path to audio file. This function also handles ``pathlib.Path`` objects,\n            but is annotated as ``str`` for TorchScript compatibility.\n\n    Returns:\n        AudioMetaData: Metadata of the given audio.\n    \"\"\"\n    # Cast to str in case type is `pathlib.Path`\n    filepath = str(filepath)\n    sinfo = torch.ops.torchaudio.sox_io_get_info(filepath)\n    return AudioMetaData(sinfo.get_sample_rate(), sinfo.get_num_frames(), sinfo.get_num_channels())\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\ndef load(\n        filepath: str,\n        frame_offset: int = 0,\n        num_frames: int = -1,\n        normalize: bool = True,\n        channels_first: bool = True,\n) -> Tuple[torch.Tensor, int]:\n    \"\"\"Load audio data from file.\n\n    Note:\n        This function can handle all the codecs that underlying libsox can handle,\n        however it is tested on the following formats;\n\n        * WAV\n\n            * 32-bit floating-point\n            * 32-bit signed integer\n            * 16-bit signed integer\n            * 8-bit unsigned integer\n\n        * MP3\n        * FLAC\n        * OGG/VORBIS\n        * OPUS\n        * SPHERE\n\n        To load ``MP3``, ``FLAC``, ``OGG/VORBIS``, ``OPUS`` and other codecs ``libsox`` does not\n        handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``\n        and corresponding codec libraries such as ``libmad`` or ``libmp3lame`` etc.\n\n    By default (``normalize=True``, ``channels_first=True``), this function returns Tensor with\n    ``float32`` dtype and the shape of ``[channel, time]``.\n    The samples are normalized to fit in the range of ``[-1.0, 1.0]``.\n\n    When the input format is WAV with integer type, such as 32-bit signed integer, 16-bit\n    signed integer and 8-bit unsigned integer (24-bit signed integer is not supported),\n    by providing ``normalize=False``, this function can return integer Tensor, where the samples\n    are expressed within the whole range of the corresponding dtype, that is, ``int32`` tensor\n    for 32-bit signed PCM, ``int16`` for 16-bit signed PCM and ``uint8`` for 8-bit unsigned PCM.\n\n    ``normalize`` parameter has no effect on 32-bit floating-point WAV and other formats, such as\n    ``flac`` and ``mp3``.\n    For these formats, this function always returns ``float32`` Tensor with values normalized to\n    ``[-1.0, 1.0]``.\n\n    Args:\n        filepath (str or pathlib.Path):\n            Path to audio file. This function also handles ``pathlib.Path`` objects, but is\n            annotated as ``str`` for TorchScript compiler compatibility.\n        frame_offset (int):\n            Number of frames to skip before start reading data.\n        num_frames (int):\n            Maximum number of frames to read. ``-1`` reads all the remaining samples,\n            starting from ``frame_offset``.\n            This function may return the less number of frames if there is not enough\n            frames in the given file.\n        normalize (bool):\n            When ``True``, this function always return ``float32``, and sample values are\n            normalized to ``[-1.0, 1.0]``.\n            If input file is integer WAV, giving ``False`` will change the resulting Tensor type to\n            integer type.\n            This argument has no effect for formats other than integer WAV type.\n        channels_first (bool):\n            When True, the returned Tensor has dimension ``[channel, time]``.\n            Otherwise, the returned Tensor's dimension is ``[time, channel]``.\n\n    Returns:\n        torch.Tensor:\n            If the input file has integer wav format and normalization is off, then it has\n            integer type, else ``float32`` type. If ``channels_first=True``, it has\n            ``[channel, time]`` else ``[time, channel]``.\n    \"\"\"\n    # Cast to str in case type is `pathlib.Path`\n    filepath = str(filepath)\n    signal = torch.ops.torchaudio.sox_io_load_audio_file(\n        filepath, frame_offset, num_frames, normalize, channels_first)\n    return signal.get_tensor(), signal.get_sample_rate()\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\ndef save(\n        filepath: str,\n        src: torch.Tensor,\n        sample_rate: int,\n        channels_first: bool = True,\n        compression: Optional[float] = None,\n):\n    \"\"\"Save audio data to file.\n\n    Note:\n        Supported formats are;\n\n        * WAV\n\n            * 32-bit floating-point\n            * 32-bit signed integer\n            * 16-bit signed integer\n            * 8-bit unsigned integer\n\n        * MP3\n        * FLAC\n        * OGG/VORBIS\n        * SPHERE\n\n        To save ``MP3``, ``FLAC``, ``OGG/VORBIS``, and other codecs ``libsox`` does not\n        handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``\n        and corresponding codec libraries such as ``libmad`` or ``libmp3lame`` etc.\n\n    Args:\n        filepath (str or pathlib.Path):\n            Path to save file. This function also handles ``pathlib.Path`` objects, but is annotated\n            as ``str`` for TorchScript compiler compatibility.\n        tensor (torch.Tensor): Audio data to save. must be 2D tensor.\n        sample_rate (int): sampling rate\n        channels_first (bool):\n            If ``True``, the given tensor is interpreted as ``[channel, time]``,\n            otherwise ``[time, channel]``.\n        compression (Optional[float]):\n            Used for formats other than WAV. This corresponds to ``-C`` option of ``sox`` command.\n\n                * | ``MP3``: Either bitrate (in ``kbps``) with quality factor, such as ``128.2``, or\n                  | VBR encoding with quality factor such as ``-4.2``. Default: ``-4.5``.\n                * | ``FLAC``: compression level. Whole number from ``0`` to ``8``.\n                  | ``8`` is default and highest compression.\n                * | ``OGG/VORBIS``: number from ``-1`` to ``10``; ``-1`` is the highest compression\n                  | and lowest quality. Default: ``3``.\n\n            See the detail at http://sox.sourceforge.net/soxformat.html.\n    \"\"\"\n    # Cast to str in case type is `pathlib.Path`\n    filepath = str(filepath)\n    if compression is None:\n        ext = str(filepath).split('.')[-1].lower()\n        if ext in ['wav', 'sph']:\n            compression = 0.\n        elif ext == 'mp3':\n            compression = -4.5\n        elif ext == 'flac':\n            compression = 8.\n        elif ext in ['ogg', 'vorbis']:\n            compression = 3.\n        else:\n            raise RuntimeError(f'Unsupported file type: \"{ext}\"')\n    signal = torch.classes.torchaudio.TensorSignal(src, sample_rate, channels_first)\n    torch.ops.torchaudio.sox_io_save_audio_file(filepath, signal, compression)\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\n@_mod_utils.deprecated('Please use \"torchaudio.load\".', '0.9.0')\ndef load_wav(\n        filepath: str,\n        frame_offset: int = 0,\n        num_frames: int = -1,\n        channels_first: bool = True,\n) -> Tuple[torch.Tensor, int]:\n    \"\"\"Load wave file.\n\n    This function is defined only for the purpose of compatibility against other backend\n    for simple usecases, such as ``torchaudio.load_wav(filepath)``.\n    The implementation is same as :py:func:`load`.\n    \"\"\"\n    return load(filepath, frame_offset, num_frames, normalize=False, channels_first=channels_first)\n", "path": "torchaudio/backend/sox_io_backend.py"}], "after_files": [{"content": "import os\nimport platform\nimport subprocess\nfrom pathlib import Path\n\nfrom torch.utils.cpp_extension import (\n    CppExtension,\n    BuildExtension as TorchBuildExtension\n)\n\n__all__ = [\n    'get_ext_modules',\n    'BuildExtension',\n]\n\n_THIS_DIR = Path(__file__).parent.resolve()\n_ROOT_DIR = _THIS_DIR.parent.parent.resolve()\n_CSRC_DIR = _ROOT_DIR / 'torchaudio' / 'csrc'\n_TP_BASE_DIR = _ROOT_DIR / 'third_party'\n_TP_INSTALL_DIR = _TP_BASE_DIR / 'install'\n\n\ndef _get_build_sox():\n    val = os.environ.get('BUILD_SOX', '0')\n    trues = ['1', 'true', 'TRUE', 'on', 'ON', 'yes', 'YES']\n    falses = ['0', 'false', 'FALSE', 'off', 'OFF', 'no', 'NO']\n    if val in trues:\n        return True\n    if val not in falses:\n        print(\n            f'WARNING: Unexpected environment variable value `BUILD_SOX={val}`. '\n            f'Expected one of {trues + falses}')\n    return False\n\n\n_BUILD_SOX = _get_build_sox()\n\n\ndef _get_eca(debug):\n    eca = []\n    if debug:\n        eca += [\"-O0\", \"-g\"]\n    else:\n        eca += [\"-O3\"]\n    return eca\n\n\ndef _get_ela(debug):\n    ela = []\n    if debug:\n        if platform.system() == \"Windows\":\n            ela += [\"/DEBUG:FULL\"]\n        else:\n            ela += [\"-O0\", \"-g\"]\n    else:\n        ela += [\"-O3\"]\n    return ela\n\n\ndef _get_srcs():\n    return [str(p) for p in _CSRC_DIR.glob('**/*.cpp')]\n\n\ndef _get_include_dirs():\n    dirs = [\n        str(_ROOT_DIR),\n    ]\n    if _BUILD_SOX:\n        dirs.append(str(_TP_INSTALL_DIR / 'include'))\n    return dirs\n\n\ndef _get_extra_objects():\n    objs = []\n    if _BUILD_SOX:\n        # NOTE: The order of the library listed bellow matters.\n        #\n        # (the most important thing is that dependencies come after a library\n        # e.g., sox comes first, flac/vorbis comes before ogg, and\n        # vorbisenc/vorbisfile comes before vorbis\n        libs = [\n            'libsox.a',\n            'libmad.a',\n            'libFLAC.a',\n            'libmp3lame.a',\n            'libopusfile.a',\n            'libopus.a',\n            'libvorbisenc.a',\n            'libvorbisfile.a',\n            'libvorbis.a',\n            'libogg.a',\n            'libopencore-amrnb.a',\n            'libopencore-amrwb.a',\n        ]\n        for lib in libs:\n            objs.append(str(_TP_INSTALL_DIR / 'lib' / lib))\n    return objs\n\n\ndef _get_libraries():\n    return [] if _BUILD_SOX else ['sox']\n\n\ndef _build_third_party():\n    build_dir = str(_TP_BASE_DIR / 'build')\n    os.makedirs(build_dir, exist_ok=True)\n    subprocess.run(\n        args=['cmake', '..'],\n        cwd=build_dir,\n        check=True,\n    )\n    subprocess.run(\n        args=['cmake', '--build', '.'],\n        cwd=build_dir,\n        check=True,\n    )\n\n\n_EXT_NAME = 'torchaudio._torchaudio'\n\n\ndef get_ext_modules(debug=False):\n    if platform.system() == 'Windows':\n        return None\n    return [\n        CppExtension(\n            _EXT_NAME,\n            _get_srcs(),\n            libraries=_get_libraries(),\n            include_dirs=_get_include_dirs(),\n            extra_compile_args=_get_eca(debug),\n            extra_objects=_get_extra_objects(),\n            extra_link_args=_get_ela(debug),\n        ),\n    ]\n\n\nclass BuildExtension(TorchBuildExtension):\n    def build_extension(self, ext):\n        if ext.name == _EXT_NAME and _BUILD_SOX:\n            _build_third_party()\n        super().build_extension(ext)\n", "path": "build_tools/setup_helpers/extension.py"}, {"content": "from typing import Tuple, Optional\n\nimport torch\nfrom torchaudio._internal import (\n    module_utils as _mod_utils,\n)\n\nfrom .common import AudioMetaData\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\ndef info(filepath: str) -> AudioMetaData:\n    \"\"\"Get signal information of an audio file.\n\n    Args:\n        filepath (str or pathlib.Path):\n            Path to audio file. This function also handles ``pathlib.Path`` objects,\n            but is annotated as ``str`` for TorchScript compatibility.\n\n    Returns:\n        AudioMetaData: Metadata of the given audio.\n    \"\"\"\n    # Cast to str in case type is `pathlib.Path`\n    filepath = str(filepath)\n    sinfo = torch.ops.torchaudio.sox_io_get_info(filepath)\n    return AudioMetaData(sinfo.get_sample_rate(), sinfo.get_num_frames(), sinfo.get_num_channels())\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\ndef load(\n        filepath: str,\n        frame_offset: int = 0,\n        num_frames: int = -1,\n        normalize: bool = True,\n        channels_first: bool = True,\n) -> Tuple[torch.Tensor, int]:\n    \"\"\"Load audio data from file.\n\n    Note:\n        This function can handle all the codecs that underlying libsox can handle,\n        however it is tested on the following formats;\n\n        * WAV, AMB\n\n            * 32-bit floating-point\n            * 32-bit signed integer\n            * 16-bit signed integer\n            * 8-bit unsigned integer (WAV only)\n\n        * MP3\n        * FLAC\n        * OGG/VORBIS\n        * OPUS\n        * SPHERE\n        * AMR-NB\n\n        To load ``MP3``, ``FLAC``, ``OGG/VORBIS``, ``OPUS`` and other codecs ``libsox`` does not\n        handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``\n        and corresponding codec libraries such as ``libmad`` or ``libmp3lame`` etc.\n\n    By default (``normalize=True``, ``channels_first=True``), this function returns Tensor with\n    ``float32`` dtype and the shape of ``[channel, time]``.\n    The samples are normalized to fit in the range of ``[-1.0, 1.0]``.\n\n    When the input format is WAV with integer type, such as 32-bit signed integer, 16-bit\n    signed integer and 8-bit unsigned integer (24-bit signed integer is not supported),\n    by providing ``normalize=False``, this function can return integer Tensor, where the samples\n    are expressed within the whole range of the corresponding dtype, that is, ``int32`` tensor\n    for 32-bit signed PCM, ``int16`` for 16-bit signed PCM and ``uint8`` for 8-bit unsigned PCM.\n\n    ``normalize`` parameter has no effect on 32-bit floating-point WAV and other formats, such as\n    ``flac`` and ``mp3``.\n    For these formats, this function always returns ``float32`` Tensor with values normalized to\n    ``[-1.0, 1.0]``.\n\n    Args:\n        filepath (str or pathlib.Path):\n            Path to audio file. This function also handles ``pathlib.Path`` objects, but is\n            annotated as ``str`` for TorchScript compiler compatibility.\n        frame_offset (int):\n            Number of frames to skip before start reading data.\n        num_frames (int):\n            Maximum number of frames to read. ``-1`` reads all the remaining samples,\n            starting from ``frame_offset``.\n            This function may return the less number of frames if there is not enough\n            frames in the given file.\n        normalize (bool):\n            When ``True``, this function always return ``float32``, and sample values are\n            normalized to ``[-1.0, 1.0]``.\n            If input file is integer WAV, giving ``False`` will change the resulting Tensor type to\n            integer type.\n            This argument has no effect for formats other than integer WAV type.\n        channels_first (bool):\n            When True, the returned Tensor has dimension ``[channel, time]``.\n            Otherwise, the returned Tensor's dimension is ``[time, channel]``.\n\n    Returns:\n        torch.Tensor:\n            If the input file has integer wav format and normalization is off, then it has\n            integer type, else ``float32`` type. If ``channels_first=True``, it has\n            ``[channel, time]`` else ``[time, channel]``.\n    \"\"\"\n    # Cast to str in case type is `pathlib.Path`\n    filepath = str(filepath)\n    signal = torch.ops.torchaudio.sox_io_load_audio_file(\n        filepath, frame_offset, num_frames, normalize, channels_first)\n    return signal.get_tensor(), signal.get_sample_rate()\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\ndef save(\n        filepath: str,\n        src: torch.Tensor,\n        sample_rate: int,\n        channels_first: bool = True,\n        compression: Optional[float] = None,\n):\n    \"\"\"Save audio data to file.\n\n    Note:\n        Supported formats are;\n\n        * WAV, AMB\n\n            * 32-bit floating-point\n            * 32-bit signed integer\n            * 16-bit signed integer\n            * 8-bit unsigned integer\n\n        * MP3\n        * FLAC\n        * OGG/VORBIS\n        * SPHERE\n        * AMR-NB\n\n        To save ``MP3``, ``FLAC``, ``OGG/VORBIS``, and other codecs ``libsox`` does not\n        handle natively, your installation of ``torchaudio`` has to be linked to ``libsox``\n        and corresponding codec libraries such as ``libmad`` or ``libmp3lame`` etc.\n\n    Args:\n        filepath (str or pathlib.Path):\n            Path to save file. This function also handles ``pathlib.Path`` objects, but is annotated\n            as ``str`` for TorchScript compiler compatibility.\n        tensor (torch.Tensor): Audio data to save. must be 2D tensor.\n        sample_rate (int): sampling rate\n        channels_first (bool):\n            If ``True``, the given tensor is interpreted as ``[channel, time]``,\n            otherwise ``[time, channel]``.\n        compression (Optional[float]):\n            Used for formats other than WAV. This corresponds to ``-C`` option of ``sox`` command.\n\n                * | ``MP3``: Either bitrate (in ``kbps``) with quality factor, such as ``128.2``, or\n                  | VBR encoding with quality factor such as ``-4.2``. Default: ``-4.5``.\n                * | ``FLAC``: compression level. Whole number from ``0`` to ``8``.\n                  | ``8`` is default and highest compression.\n                * | ``OGG/VORBIS``: number from ``-1`` to ``10``; ``-1`` is the highest compression\n                  | and lowest quality. Default: ``3``.\n\n            See the detail at http://sox.sourceforge.net/soxformat.html.\n    \"\"\"\n    # Cast to str in case type is `pathlib.Path`\n    filepath = str(filepath)\n    if compression is None:\n        ext = str(filepath).split('.')[-1].lower()\n        if ext in ['wav', 'sph', 'amb', 'amr-nb']:\n            compression = 0.\n        elif ext == 'mp3':\n            compression = -4.5\n        elif ext == 'flac':\n            compression = 8.\n        elif ext in ['ogg', 'vorbis']:\n            compression = 3.\n        else:\n            raise RuntimeError(f'Unsupported file type: \"{ext}\"')\n    signal = torch.classes.torchaudio.TensorSignal(src, sample_rate, channels_first)\n    torch.ops.torchaudio.sox_io_save_audio_file(filepath, signal, compression)\n\n\n@_mod_utils.requires_module('torchaudio._torchaudio')\n@_mod_utils.deprecated('Please use \"torchaudio.load\".', '0.9.0')\ndef load_wav(\n        filepath: str,\n        frame_offset: int = 0,\n        num_frames: int = -1,\n        channels_first: bool = True,\n) -> Tuple[torch.Tensor, int]:\n    \"\"\"Load wave file.\n\n    This function is defined only for the purpose of compatibility against other backend\n    for simple usecases, such as ``torchaudio.load_wav(filepath)``.\n    The implementation is same as :py:func:`load`.\n    \"\"\"\n    return load(filepath, frame_offset, num_frames, normalize=False, channels_first=channels_first)\n", "path": "torchaudio/backend/sox_io_backend.py"}]}