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
python类Error()的实例源码
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())
def is_good_wave(filename):
"""Check if the wave is in correct format for LIUM.
:type filename: string
:param filename: file to check"""
import wave
par = None
try:
w_file = wave.open(filename)
par = w_file.getparams()
w_file.close()
except wave.Error, exc:
print exc
return False
if par[:3] == (1, 2, 16000) and par[-1:] == ('not compressed',):
return True
else:
return False
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())
def validate_wave(ctx, param, value):
"""
Validate the wave file by trying to open it
and checking that its got a single channel.
:param ctx:<class 'click.core.Context'>
:param param:<class 'click.core.Option'>
:param value:str
:return:<class 'wave.Wave_read'>
"""
try:
wave_read = wave.open(value)
if wave_read.getnchannels() != 1:
raise click.BadParameter('Only mono wave files are supported')
return wave_read
except wave.Error as e:
raise click.BadParameter('Not a valid wave file. {}'.format(e.__str__()))
def play_sound(sound):
try:
wf = wave.open(sound, 'rb')
# instantiate PyAudio (1)
p = pyaudio.PyAudio()
# define callback (2)
def callback(in_data, frame_count, time_info, status):
data = wf.readframes(frame_count)
return (data, pyaudio.paContinue)
# open stream using callback (3)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True,
stream_callback=callback)
# start the stream (4)
stream.start_stream()
except wave.Error:
print('Warning: caught wave.Error!')
def _wave(self):
"""Return a wave.Wave_read instance from the ``wave`` module."""
try:
return wave.open(StringIO(self.contents))
except wave.Error, err:
err.message += "\nInvalid wave file: %s" % self
err.args = (err.message,)
raise
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
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())
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())
def show_protocol_selection_in_interpretation(self, start_message, start, end_message, end):
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()
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
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
def setWave(self, file):
try:
wavestream = wave.open(str(file.toUtf8()))
self.file = file
self.info_lbl.setText('')
except wave.Error:
self.file = None
self.stream = None
self.info_lbl.setText('Unknown or unsupported format')
self.clear_labels()
self.set_valid(False)
self.info_icon.setVisible(True)
return
except:
self.file = None
self.stream = None
self.info_lbl.setText('')
self.clear_labels()
self.set_valid(False)
self.info_icon.setVisible(False)
return
channels = wavestream.getnchannels()
sampwidth = wavestream.getsampwidth()
if channels == 1:
chan_txt = 'Mono'
elif channels == 2:
chan_txt = 'Stereo'
else:
chan_txt = str(channels)
framerate = wavestream.getframerate()
frames = wavestream.getnframes()
length = frames/float(framerate)
self.channels_lbl.setText(chan_txt)
self.sampwidth_lbl.setText('{} bit'.format(sampwidth*8))
self.framerate_lbl.setText('{} Hz'.format(framerate))
self.frames_lbl.setText(str(frames))
self.length_lbl.setText(secs2time(length))
if channels > 2:
self.info_lbl.setText('Too many channels: only mono or stereo files are supported.')
self.info_icon.setVisible(True)
self.set_valid(False)
elif sampwidth > 2:
self.info_lbl.setText('Only 8bit and 16 bit sample resolutions are accepted.')
self.info_icon.setVisible(True)
self.set_valid(False)
elif length > 60:
self.info_lbl.setText('File too long, please select a file with length less than a minute.')
self.info_icon.setVisible(True)
self.set_valid(False)
else:
self.set_valid(file, wavestream)
def add_files(self, filepaths, group_id=0, enforce_sample_rate=None):
num_files = len(filepaths)
if num_files == 0:
return
for i, filename in enumerate(filepaths):
if not os.path.exists(filename):
continue
if os.path.isdir(filename):
for f in self.signal_tab_controller.signal_frames:
self.close_signal_frame(f)
FileOperator.RECENT_PATH = filename
self.project_manager.set_project_folder(filename)
return
FileOperator.RECENT_PATH = os.path.split(filename)[0]
if filename.endswith(".complex"):
self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate)
elif filename.endswith(".coco"):
self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate)
elif filename.endswith(".proto") or filename.endswith(".proto.xml"):
self.add_protocol_file(filename)
elif filename.endswith(".wav"):
try:
import wave
w = wave.open(filename)
w.close()
except wave.Error as e:
Errors.generic_error("Unsupported WAV type", "Only uncompressed WAVs (PCM) are supported.", str(e))
continue
self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate)
elif filename.endswith(".fuzz") or filename.endswith(".fuzz.xml"):
self.add_fuzz_profile(filename)
elif filename.endswith(".txt"):
self.add_plain_bits_from_txt(filename)
elif filename.endswith(".csv"):
self.__import_csv(filename, group_id)
continue
elif os.path.basename(filename) == constants.PROJECT_FILE:
self.project_manager.set_project_folder(os.path.split(filename)[0])
else:
self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate)
if self.project_manager.project_file is None:
self.adjust_for_current_file(filename)
def __enter__(self):
assert self.stream is None, "This audio source is already inside a context manager"
try:
# attempt to read the file as WAV
self.audio_reader = wave.open(self.filename_or_fileobject, "rb")
self.little_endian = True # RIFF WAV is a little-endian format (most ``audioop`` operations assume that the frames are stored in little-endian form)
except wave.Error:
try:
# attempt to read the file as AIFF
self.audio_reader = aifc.open(self.filename_or_fileobject, "rb")
self.little_endian = False # AIFF is a big-endian format
except aifc.Error:
# attempt to read the file as FLAC
if hasattr(self.filename_or_fileobject, "read"):
flac_data = self.filename_or_fileobject.read()
else:
with open(self.filename_or_fileobject, "rb") as f: flac_data = f.read()
# run the FLAC converter with the FLAC data to get the AIFF data
flac_converter = get_flac_converter()
process = subprocess.Popen([
flac_converter,
"--stdout", "--totally-silent", # put the resulting AIFF file in stdout, and make sure it's not mixed with any program output
"--decode", "--force-aiff-format", # decode the FLAC file into an AIFF file
"-", # the input FLAC file contents will be given in stdin
], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
aiff_data, stderr = process.communicate(flac_data)
aiff_file = io.BytesIO(aiff_data)
try:
self.audio_reader = aifc.open(aiff_file, "rb")
except aifc.Error:
assert False, "Audio file could not be read as WAV, AIFF, or FLAC; check if file is corrupted"
self.little_endian = False # AIFF is a big-endian format
assert 1 <= self.audio_reader.getnchannels() <= 2, "Audio must be mono or stereo"
self.SAMPLE_WIDTH = self.audio_reader.getsampwidth()
# 24-bit audio needs some special handling for old Python versions (workaround for https://bugs.python.org/issue12866)
samples_24_bit_pretending_to_be_32_bit = False
if self.SAMPLE_WIDTH == 3: # 24-bit audio
try: audioop.bias(b"", self.SAMPLE_WIDTH, 0) # test whether this sample width is supported (for example, ``audioop`` in Python 3.3 and below don't support sample width 3, while Python 3.4+ do)
except audioop.error: # this version of audioop doesn't support 24-bit audio (probably Python 3.3 or less)
samples_24_bit_pretending_to_be_32_bit = True # while the ``AudioFile`` instance will outwardly appear to be 32-bit, it will actually internally be 24-bit
self.SAMPLE_WIDTH = 4 # the ``AudioFile`` instance should present itself as a 32-bit stream now, since we'll be converting into 32-bit on the fly when reading
self.SAMPLE_RATE = self.audio_reader.getframerate()
self.CHUNK = 4096
self.FRAME_COUNT = self.audio_reader.getnframes()
self.DURATION = self.FRAME_COUNT / float(self.SAMPLE_RATE)
self.stream = AudioFile.AudioFileStream(self.audio_reader, self.little_endian, samples_24_bit_pretending_to_be_32_bit)
return self