本文整理匯總了Python中wave.Error方法的典型用法代碼示例。如果您正苦於以下問題:Python wave.Error方法的具體用法?Python wave.Error怎麽用?Python wave.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類wave
的用法示例。
在下文中一共展示了wave.Error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _read_audio
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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
示例2: _read_fmt_chunk
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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'
示例3: _is_good_wave
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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
示例4: test_unpickling_object_that_is_not_imported_raises_error
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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)
示例5: test_aifc
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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())
示例6: _scan_wave
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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.
示例7: __init__
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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()
示例8: readin
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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
示例9: __init__
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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
示例10: wav_read
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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
示例11: test_wav
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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())
示例12: read_wave_file
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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
示例13: test_wav
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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())
示例14: generate_dir
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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
示例15: clean_dir
# 需要導入模塊: import wave [as 別名]
# 或者: from wave import Error [as 別名]
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