Skip to content

Commit

Permalink
support reading from a wavefile stored in a zip archive
Browse files Browse the repository at this point in the history
  • Loading branch information
dmeliza committed Aug 29, 2024
1 parent 7c0733a commit ae8c867
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
10 changes: 7 additions & 3 deletions ewave.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
WAVE_FORMAT_IEEE_FLOAT = 0x0003
WAVE_FORMAT_EXTENSIBLE = 0xFFFE

__version__ = "1.0.8"
__version__ = "1.0.9"


class Error(Exception):
Expand Down Expand Up @@ -173,7 +173,10 @@ def flush(self):
return self

def read(
self, frames: Optional[int] = None, offset: int = 0, memmap: str = "c"
self,
frames: Optional[int] = None,
offset: int = 0,
memmap: Union[str, bool, None] = "c",
) -> np.ndarray:
"""Returns acoustic data from file.
Expand Down Expand Up @@ -212,7 +215,8 @@ def read(
else:
pos = self.fp.tell()
self.fp.seek(coff)
A = np.fromfile(self.fp, dtype=self._dtype, count=frames * self.nchannels)
data = self.fp.read(frames * self.nchannels * self._dtype.itemsize)
A = np.frombuffer(data, dtype=self._dtype)
self.fp.seek(pos)

if self.nchannels > 1:
Expand Down
22 changes: 22 additions & 0 deletions test_ewave.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,5 +221,27 @@ def test15_append(tmp_file):
assert_array_almost_equal(np.concatenate([d1, d2]), fp.read())


def test16_read_from_zip(tmp_path):
from zipfile import ZipFile

wav_name = "test.wav"
tmp_file = tmp_path / wav_name
tmp_zip = tmp_path / "test.zip"
src_data = np.random.randn(10000, nchan)
with ewave.open(tmp_file, "w+", sampling_rate=Fs, dtype="f", nchannels=nchan) as fp:
fp.write(src_data)

with ZipFile(tmp_zip, "w") as archive:
archive.write(tmp_file, arcname=wav_name)

with ZipFile(tmp_zip, "r") as archive:
with archive.open(wav_name) as zipped_wave:
with ewave.open(zipped_wave, "r") as fp:
assert fp.sampling_rate == Fs
assert fp.nchannels == nchan
dst_data = fp.read(memmap=False)
assert_array_almost_equal(src_data, dst_data)


# Variables:
# End:

0 comments on commit ae8c867

Please sign in to comment.