Python wave.Error() Examples

The following are 30 code examples of wave.Error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wave , or try the search function .
Example #1
Source File: recognition.py    From Piwho with MIT License 7 votes vote down vote up
def _is_good_wave(self, filename):
        """
        check if wav is in correct format for MARF.
        """
        par = None
        try:
            w_file = wave.open(filename)
            par = w_file.getparams()
            w_file.close()
        except wave.Error as exc:
            print (exc)
            return False

        if par[:3] == (1, 2, 8000) and par[-1:] == ('not compressed',):
            return True
        else:
            return False 
Example #2
Source File: sndhdr.py    From odoo13-x64 with GNU General Public License v3.0 6 votes vote down vote up
def test_aifc(h, f):
    import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(),
            a.getnframes(), 8 * a.getsampwidth()) 
Example #3
Source File: model.py    From MAX-Speech-to-Text-Converter with Apache License 2.0 6 votes vote down vote up
def _read_audio(self, audio_data):

        try:
            fin = wave.open(io.BytesIO(audio_data))
        except (wave.Error, EOFError):
            raise OSError("Error reading the audio file. Only WAV files are supported.")

        if fin.getnchannels() != 1:
            raise OSError("Only mono audio files are supported.")

        fin_len = fin.getnframes() / fin.getframerate()  # num frames / frame rate = length in seconds

        if fin_len > 10:
            raise OSError("This model is designed to work with short (about 5 second) audio files only.")

        return fin 
Example #4
Source File: sndhdr.py    From android_universal with MIT License 6 votes vote down vote up
def test_aifc(h, f):
    import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(),
            a.getnframes(), 8 * a.getsampwidth()) 
Example #5
Source File: audio.py    From pyaaf2 with MIT License 6 votes vote down vote up
def _read_fmt_chunk(self, chunk):

        # added support for wave extensible

        wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from(b'<HHLLH', chunk.read(14))
        if wFormatTag in  (wave.WAVE_FORMAT_PCM, WAVE_EXTENSIBLE_PCM):
            sampwidth = struct.unpack_from(b'<H', chunk.read(2))[0]
            self._sampwidth = (sampwidth + 7) // 8
        else:
            raise wave.Error('unknown format: %r' % (wFormatTag,))

        if not self._sampwidth in (2, 3):
            raise wave.Error('unsupported sample width: %r' % (self._sampwidth,))

        self._framesize = self._nchannels * self._sampwidth
        self._comptype = 'NONE'
        self._blockalign = wBlockAlign
        self._compname = 'not compressed' 
Example #6
Source File: test_serialization.py    From deepdiff with MIT License 6 votes vote down vote up
def test_unpickling_object_that_is_not_imported_raises_error(self):

        def get_the_pickle():
            import wave
            obj = wave.Error
            return pickle_dump(obj)

        serialized = get_the_pickle()
        # Making sure that the module is unloaded.
        del sys.modules['wave']
        module_dot_name = 'wave.Error'

        expected_msg = MODULE_NOT_FOUND_MSG.format(module_dot_name)
        with pytest.raises(ModuleNotFoundError) as excinfo:
            pickle_load(serialized, safe_to_import=module_dot_name)
        assert expected_msg == str(excinfo.value) 
Example #7
Source File: sndhdr.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_aifc(h, f):
    import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(),
            a.getnframes(), 8 * a.getsampwidth()) 
Example #8
Source File: sndhdr.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_aifc(h, f):
    import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(),
            a.getnframes(), 8 * a.getsampwidth()) 
Example #9
Source File: sndhdr.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_aifc(h, f):
    import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(),
            a.getnframes(), 8 * a.getsampwidth()) 
Example #10
Source File: sndhdr.py    From Imogen with MIT License 6 votes vote down vote up
def test_aifc(h, f):
    import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(),
            a.getnframes(), 8 * a.getsampwidth()) 
Example #11
Source File: audio.py    From shennong with GNU General Public License v3.0 6 votes vote down vote up
def _scan_wave(cls, wav_file):
        """Scan the `wav_file` using soxi

        Support only for integer formats but efficient implementation.

        """
        try:
            with wave.open(wav_file, 'r') as fwav:
                return cls._metawav(
                    fwav.getnchannels(),
                    fwav.getframerate(),
                    fwav.getnframes(),
                    fwav.getnframes() / fwav.getframerate())
        except wave.Error:
            raise ValueError(
                '{}: cannot read file, is it a wav?'.format(wav_file))

    # we use a memoize cache because Audio.load is often called to
    # load only segments of a file. So the cache avoid to reload again
    # and again the same file to extract only a chunk of it. A little
    # maxsize is enough because access to audio chunks are usually
    # ordered. 
Example #12
Source File: sndhdr.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_aifc(h, f):
    import aifc
    if not h.startswith(b'FORM'):
        return None
    if h[8:12] == b'AIFC':
        fmt = 'aifc'
    elif h[8:12] == b'AIFF':
        fmt = 'aiff'
    else:
        return None
    f.seek(0)
    try:
        a = aifc.open(f, 'r')
    except (EOFError, aifc.Error):
        return None
    return (fmt, a.getframerate(), a.getnchannels(),
            a.getnframes(), 8 * a.getsampwidth()) 
Example #13
Source File: wave.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, filename, file=None):
        if file is None:
            file = open(filename, 'rb')

        self._file = file

        try:
            self._wave = wave.open(file)
        except wave.Error as e:
            raise WAVEDecodeException(e)

        nchannels, sampwidth, framerate, nframes, comptype, compname = self._wave.getparams()

        self.audio_format = AudioFormat(channels=nchannels, sample_size=sampwidth * 8, sample_rate=framerate)

        self._bytes_per_frame = nchannels * sampwidth
        self._duration = nframes / framerate
        self._duration_per_frame = self._duration / nframes
        self._num_frames = nframes

        self._wave.rewind() 
Example #14
Source File: test_speech.py    From python-dlpy with Apache License 2.0 5 votes vote down vote up
def test_read_audio_1(self):
        try:
            import wave
        except ImportError:
            unittest.TestCase.skipTest(self, "wave is not found in the libraries.")

        if self.data_dir_local is None:
            unittest.TestCase.skipTest(self, "DLPY_DATA_DIR_LOCAL is not set in the environment variables.")

        with self.assertRaises(wave.Error):
            read_audio(os.path.join(self.data_dir_local, "sample_acoustic_model.sashdat"))
        with self.assertRaises(wave.Error):
            read_audio(os.path.join(self.data_dir_local, "sample_language_model.csv")) 
Example #15
Source File: sndhdr.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.open(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #16
Source File: manage_audio.py    From honk with MIT License 5 votes vote down vote up
def generate_dir(directory):
    for filename in os.listdir(directory):
        fullpath = os.path.join(os.path.abspath(directory), filename)
        try:
            with wave.open(fullpath) as f:
                n_channels = f.getnchannels()
                width = f.getsampwidth()
                rate = f.getframerate()
                snippet = AudioSnippet(f.readframes(16000))
            for i, e in enumerate(snippet.generate_contrastive()):
                gen_name = os.path.join(directory, "gen-{}-{}".format(i, filename))
                e.save(gen_name)
            print("Generated from {}".format(filename))
        except (wave.Error, IsADirectoryError, PermissionError) as e:
            pass 
Example #17
Source File: manage_audio.py    From honk with MIT License 5 votes vote down vote up
def clean_dir(directory=".", cutoff_ms=1000):
    """Trims all audio in directory to the loudest window of length cutoff_ms. 1 second is consistent
    with the speech command dataset.

    Args:
        directory: The directory containing all the .wav files. Should have nothing but .wav
        cutoff_ms: The length of time to trim audio to in milliseconds
    """
    for filename in os.listdir(directory):
        fullpath = os.path.join(directory, filename)
        try:
            with wave.open(fullpath) as f:
                n_channels = f.getnchannels()
                width = f.getsampwidth()
                rate = f.getframerate()
                n_samples = int((cutoff_ms / 1000) * rate)
                snippet = AudioSnippet(f.readframes(10 * n_samples))
            snippet.trim_window(n_samples * width)
            with wave.open(fullpath, "w") as f:
                f.setnchannels(n_channels)
                f.setsampwidth(width)
                f.setframerate(rate)
                f.writeframes(snippet.byte_data)
            print("Trimmed {} to {} ms".format(filename, cutoff_ms))
        except (wave.Error, IsADirectoryError, PermissionError) as e:
            pass 
Example #18
Source File: MainController.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def show_protocol_selection_in_interpretation(self, start_message, start, end_message, end):
        try:
            cfc = self.compare_frame_controller
            msg_total = 0
            last_sig_frame = None
            for protocol in cfc.protocol_list:
                if not protocol.show:
                    continue
                n = protocol.num_messages
                view_type = cfc.ui.cbProtoView.currentIndex()
                messages = [i - msg_total for i in range(msg_total, msg_total + n) if start_message <= i <= end_message]
                if len(messages) > 0:
                    try:
                        signal_frame = next((sf for sf, pf in self.signal_protocol_dict.items() if pf == protocol))
                    except StopIteration:
                        QMessageBox.critical(self, self.tr("Error"),
                                             self.tr("Could not find corresponding signal frame."))
                        return
                    signal_frame.set_roi_from_protocol_analysis(min(messages), start, max(messages), end + 1, view_type)
                    last_sig_frame = signal_frame
                msg_total += n
            focus_frame = last_sig_frame
            if last_sig_frame is not None:
                self.signal_tab_controller.ui.scrollArea.ensureWidgetVisible(last_sig_frame, 0, 0)

            QApplication.instance().processEvents()
            self.ui.tabWidget.setCurrentIndex(0)
            if focus_frame is not None:
                focus_frame.ui.txtEdProto.setFocus()
        except Exception as e:
            logger.exception(e) 
Example #19
Source File: __init__.py    From mocktailsmixer with MIT License 5 votes vote down vote up
def __init__(self, fp, sample_rate, sample_width):
        self._fp = fp
        try:
            self._wavep = wave.open(self._fp, 'r')
        except wave.Error as e:
            logging.warning('error opening WAV file: %s, '
                            'falling back to RAW format', e)
            self._fp.seek(0)
            self._wavep = None
        self._sample_rate = sample_rate
        self._sample_width = sample_width
        self._sleep_until = 0 
Example #20
Source File: sndhdr.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.open(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #21
Source File: sndhdr.py    From android_universal with MIT License 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.open(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #22
Source File: sndhdr.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.openfp(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #23
Source File: audio_helpers.py    From bot with MIT License 5 votes vote down vote up
def __init__(self, fp, sample_rate, sample_width):
        self._fp = fp
        try:
            self._wavep = wave.open(self._fp, 'r')
        except wave.Error as e:
            logging.warning('error opening WAV file: %s, '
                            'falling back to RAW format', e)
            self._fp.seek(0)
            self._wavep = None
        self._sample_rate = sample_rate
        self._sample_width = sample_width
        self._sleep_until = 0 
Example #24
Source File: sndhdr.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.openfp(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #25
Source File: sndhdr.py    From Imogen with MIT License 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.open(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #26
Source File: wavio.py    From SampleScanner with MIT License 5 votes vote down vote up
def read_wave_file(filename, use_numpy=False):
    try:
        w = wave.open(filename)
        a = numpy.fromstring(w.readframes(9999999999), dtype=NUMPY_DTYPE)
        if use_numpy:
            return numpy.reshape(a, (w.getnchannels(), -1), 'F')
        else:
            return [
                a[i::w.getnchannels()]
                for i in xrange(w.getnchannels())
            ]
    except wave.Error:
        print "Could not open %s" % filename
        raise 
Example #27
Source File: sndhdr.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_wav(h, f):
    import wave
    # 'RIFF' <len> 'WAVE' 'fmt ' <len>
    if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
        return None
    f.seek(0)
    try:
        w = wave.openfp(f, 'r')
    except (EOFError, wave.Error):
        return None
    return ('wav', w.getframerate(), w.getnchannels(),
                   w.getnframes(), 8*w.getsampwidth()) 
Example #28
Source File: audio_io.py    From autosynch with GNU General Public License v3.0 5 votes vote down vote up
def wav_read(file_name, mono=False):
    """Reads a wav file and returns it data. If `mono` is \
    set to true, the returned audio data are monophonic.

    :param file_name: The file name of the wav file.
    :type file_name: str
    :param mono: Get mono version.
    :type mono: bool
    :return: The data and the sample rate.
    :rtype: (numpy.core.multiarray.ndarray, int)
    """
    try:
        samples, sample_rate = _load_wav_with_wave(file_name)
        with wave.open(file_name) as wav:
            sample_width = wav.getsampwidth()

        if sample_width == 1:
            # 8 bit case
            samples = (samples.astype(float) / _normFact['int8']) - 1.0
        elif sample_width == 2:
            # 16 bit case
            samples = samples.astype(float) / _normFact['int16']
        elif sample_width == 3:
            # 24 bit case
            samples = samples.astype(float) / _normFact['int24']
    except wave.Error:
        # 32 bit case
        samples, sample_rate = _load_wav_with_scipy(file_name)

    if samples.shape[1] == 1:
        samples = samples.squeeze(-1)

    # mono conversion
    if mono and samples.ndim == 2:
        samples = (samples[:, 0] + samples[:, 1]) * 0.5

    return samples, sample_rate 
Example #29
Source File: audio_helpers.py    From assistant-sdk-python with Apache License 2.0 5 votes vote down vote up
def __init__(self, fp, sample_rate, sample_width):
        self._fp = fp
        try:
            self._wavep = wave.open(self._fp, 'r')
        except wave.Error as e:
            logging.warning('error opening WAV file: %s, '
                            'falling back to RAW format', e)
            self._fp.seek(0)
            self._wavep = None
        self._sample_rate = sample_rate
        self._sample_width = sample_width
        self._sleep_until = 0 
Example #30
Source File: rattlesnake.py    From rattlesnake with MIT License 5 votes vote down vote up
def readin(file):
    """
    Reads in the given wave file and returns a new PyAudio stream object from it.

    :param file: The path to the file to read in
    :return (waveform, stream): (The actual audio data as a waveform, the PyAudio object for said data)
    """

    # Open the waveform from the command argument
    try:
        waveform = wave.open(file, 'r')
    except wave.Error:
        print('The program can only process wave audio files (.wav)')
        sys.exit()
    except FileNotFoundError:
        print('The chosen file does not exist')
        sys.exit()

    # Load PyAudio and create a useable waveform object
    stream = pa.open(
        format=pa.get_format_from_width(waveform.getsampwidth()),
        channels=waveform.getnchannels(),
        rate=waveform.getframerate(),
        output=True
    )

    # Return the waveform as well as the generated PyAudio stream object
    return waveform, stream