.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/loading_saving/plot_stream_a_long_file.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_loading_saving_plot_stream_a_long_file.py: Read a long file in blocks ========================== ``io.StreamedAudioReader`` decodes on demand, so a long file does not have to fit in memory. This example computes the RMS level of each second from a one-minute file and reads only one block at a time. .. GENERATED FROM PYTHON SOURCE LINES 9-18 .. code-block:: Python import tempfile from pathlib import Path import matplotlib.pyplot as plt import numpy as np import audio_samples as aus .. GENERATED FROM PYTHON SOURCE LINES 19-20 Write a minute of noise whose level rises and falls. .. GENERATED FROM PYTHON SOURCE LINES 20-27 .. code-block:: Python sr = 8000 t = np.arange(60 * sr) / sr level = 0.1 + 0.4 * (1 + np.sin(2 * np.pi * t / 30.0)) / 2 y = (level * np.random.default_rng(0).standard_normal(t.size)).astype(np.float32) path = Path(tempfile.mkdtemp()) / "long.flac" aus.io.save(str(path), aus.AudioSamples.new_mono(y, sr).as_i16()) .. GENERATED FROM PYTHON SOURCE LINES 28-30 Read one second at a time. ``read_frames`` returns an array, or ``None`` at the end of the file. .. GENERATED FROM PYTHON SOURCE LINES 30-43 .. code-block:: Python levels = [] with aus.io.StreamedAudioReader(str(path)) as reader: while True: block = reader.read_frames(sr, dtype=aus.SampleType.F32) if block is None: break levels.append(float(np.sqrt(np.mean(block**2)))) assert len(levels) == 60 fig, ax = plt.subplots(figsize=(7, 3)) ax.plot(levels) ax.set(xlabel="Time (s)", ylabel="RMS", title="RMS per second, read in blocks") .. image-sg:: /gallery/loading_saving/images/sphx_glr_plot_stream_a_long_file_001.png :alt: RMS per second, read in blocks :srcset: /gallery/loading_saving/images/sphx_glr_plot_stream_a_long_file_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none [Text(0.5, 3.833333333333327, 'Time (s)'), Text(50.222222222222214, 0.5, 'RMS'), Text(0.5, 1.0, 'RMS per second, read in blocks')] .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.141 seconds) .. _sphx_glr_download_gallery_loading_saving_plot_stream_a_long_file.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_stream_a_long_file.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_stream_a_long_file.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_stream_a_long_file.zip `