本文整理汇总了Python中audiotools.bitstream.BitstreamReader.rewind方法的典型用法代码示例。如果您正苦于以下问题:Python BitstreamReader.rewind方法的具体用法?Python BitstreamReader.rewind怎么用?Python BitstreamReader.rewind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类audiotools.bitstream.BitstreamReader
的用法示例。
在下文中一共展示了BitstreamReader.rewind方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __find_next_mp3_frame__
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
def __find_next_mp3_frame__(cls, mp3file):
from audiotools.id3 import skip_id3v2_comment
# if we're starting at an ID3v2 header, skip it to save a bunch of time
bytes_skipped = skip_id3v2_comment(mp3file)
# then find the next mp3 frame
from audiotools.bitstream import BitstreamReader
reader = BitstreamReader(mp3file, 0)
reader.mark()
try:
(sync,
mpeg_id,
layer_description) = reader.parse("11u 2u 2u 1p")
except IOError as err:
reader.unmark()
raise err
while (not ((sync == 0x7FF) and
(mpeg_id in (0, 2, 3)) and
(layer_description in (1, 2, 3)))):
reader.rewind()
reader.unmark()
reader.skip(8)
bytes_skipped += 1
reader.mark()
try:
(sync,
mpeg_id,
layer_description) = reader.parse("11u 2u 2u 1p")
except IOError as err:
reader.unmark()
raise err
else:
reader.rewind()
reader.unmark()
return bytes_skipped
示例2: __find_mp3_start__
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
def __find_mp3_start__(cls, mp3file):
"""places mp3file at the position of the MP3 file's start"""
from audiotools.id3 import skip_id3v2_comment
# if we're starting at an ID3v2 header, skip it to save a bunch of time
skip_id3v2_comment(mp3file)
from audiotools.bitstream import BitstreamReader
reader = BitstreamReader(mp3file, 0)
# skip over any bytes that aren't a valid MPEG header
reader.mark()
(frame_sync, mpeg_id, layer) = reader.parse("11u 2u 2u 1p")
while (not ((frame_sync == 0x7FF) and
(mpeg_id in (0, 2, 3)) and
(layer in (1, 2, 3)))):
reader.rewind()
reader.unmark()
reader.skip(8)
reader.mark()
reader.rewind()
reader.unmark()
示例3: __init__
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
class WavPackDecoder:
def __init__(self, filename):
self.reader = BitstreamReader(open(filename, "rb"), 1)
#read initial block to populate
#sample_rate, bits_per_sample, channels, and channel_mask
self.reader.mark()
block_header = Block_Header.read(self.reader)
sub_blocks_size = block_header.block_size - 24
sub_blocks_data = self.reader.substream(sub_blocks_size)
if (block_header.sample_rate != 15):
self.sample_rate = [6000, 8000, 9600, 11025, 12000,
16000, 22050, 24000, 32000, 44100,
48000, 64000, 88200, 96000,
192000][block_header.sample_rate]
else:
sub_blocks_data.mark()
try:
for sub_block in sub_blocks(sub_blocks_data, sub_blocks_size):
if ((sub_block.metadata_function == 7) and
(sub_block.nondecoder_data == 1)):
self.sample_rate = sub_block.data.read(
sub_block.data_size() * 8)
break
else:
raise ValueError("invalid sample rate")
finally:
sub_blocks_data.rewind()
sub_blocks_data.unmark()
self.bits_per_sample = [8, 16, 24, 32][block_header.bits_per_sample]
if (block_header.initial_block and block_header.final_block):
if ((block_header.mono_output == 0) or
(block_header.false_stereo == 1)):
self.channels = 2
self.channel_mask = 0x3
else:
self.channels = 1
self.channel_mask = 0x4
else:
#look for channel mask sub block
sub_blocks_data.mark()
for sub_block in sub_blocks(sub_blocks_data, sub_blocks_size):
if ((sub_block.metadata_function == 13) and
(sub_block.nondecoder_data == 0)):
self.channels = sub_block.data.read(8)
self.channel_mask = sub_block.data.read(
(sub_block.data_size() - 1) * 8)
break
else:
#FIXME - handle case of no channel mask sub block
raise NotImplementedError()
sub_blocks_data.rewind()
sub_blocks_data.unmark()
self.reader.rewind()
self.reader.unmark()
self.pcm_finished = False
self.md5_checked = False
self.md5sum = md5()
def read(self, bytes):
if (self.pcm_finished):
if (not self.md5_checked):
self.reader.mark()
try:
try:
header = Block_Header.read(self.reader)
sub_blocks_size = header.block_size - 24
sub_blocks_data = self.reader.substream(sub_blocks_size)
for sub_block in sub_blocks(sub_blocks_data,
sub_blocks_size):
if ((sub_block.metadata_function == 6) and
(sub_block.nondecoder_data == 1)):
if (sub_block.data.read_bytes(16) !=
self.md5sum.digest()):
raise ValueError("invalid stream MD5 sum")
except (IOError, ValueError):
#no error if a block isn't found
pass
finally:
self.reader.rewind()
self.reader.unmark()
return from_list([], self.channels, self.bits_per_sample, True)
channels = []
while (True): #in place of a do-while loop
try:
block_header = Block_Header.read(self.reader)
except (ValueError, IOError):
self.pcm_finished = True
return from_list([], self.channels, self.bits_per_sample, True)
sub_blocks_size = block_header.block_size - 24
sub_blocks_data = self.reader.substream(sub_blocks_size)
channels.extend(read_block(block_header,
sub_blocks_size,
sub_blocks_data))
#.........这里部分代码省略.........
示例4: __read_info__
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
def __read_info__(self):
from audiotools.bitstream import BitstreamReader
from audiotools import ChannelMask
reader = BitstreamReader(open(self.filename, "rb"), 1)
reader.mark()
try:
(block_id,
total_samples,
bits_per_sample,
mono_output,
initial_block,
final_block,
sample_rate) = reader.parse(
"4b 64p 32u 64p 2u 1u 8p 1u 1u 5p 5p 4u 37p")
if (block_id != 'wvpk'):
from audiotools.text import ERR_WAVPACK_INVALID_HEADER
raise InvalidWavPack(ERR_WAVPACK_INVALID_HEADER)
if (sample_rate != 0xF):
self.__samplerate__ = WavPackAudio.SAMPLING_RATE[sample_rate]
else:
# if unknown, pull from SAMPLE_RATE sub-block
for (block_id,
nondecoder,
data_size,
data) in self.sub_blocks(reader):
if ((block_id == 0x7) and nondecoder):
self.__samplerate__ = data.read(data_size * 8)
break
else:
# no SAMPLE RATE sub-block found
# so pull info from FMT chunk
reader.rewind()
(self.__samplerate__,) = self.fmt_chunk(reader).parse(
"32p 32u")
self.__bitspersample__ = [8, 16, 24, 32][bits_per_sample]
self.__total_frames__ = total_samples
if (initial_block and final_block):
if (mono_output):
self.__channels__ = 1
self.__channel_mask__ = ChannelMask(0x4)
else:
self.__channels__ = 2
self.__channel_mask__ = ChannelMask(0x3)
else:
# if not mono or stereo, pull from CHANNEL INFO sub-block
reader.rewind()
for (block_id,
nondecoder,
data_size,
data) in self.sub_blocks(reader):
if ((block_id == 0xD) and not nondecoder):
self.__channels__ = data.read(8)
self.__channel_mask__ = ChannelMask(
data.read((data_size - 1) * 8))
break
else:
# no CHANNEL INFO sub-block found
# so pull info from FMT chunk
reader.rewind()
fmt = self.fmt_chunk(reader)
compression_code = fmt.read(16)
self.__channels__ = fmt.read(16)
if (compression_code == 1):
# this is theoretically possible
# with very old .wav files,
# but shouldn't happen in practice
self.__channel_mask__ = \
{1: ChannelMask.from_fields(front_center=True),
2: ChannelMask.from_fields(front_left=True,
front_right=True),
3: ChannelMask.from_fields(front_left=True,
front_right=True,
front_center=True),
4: ChannelMask.from_fields(front_left=True,
front_right=True,
back_left=True,
back_right=True),
5: ChannelMask.from_fields(front_left=True,
front_right=True,
back_left=True,
back_right=True,
front_center=True),
6: ChannelMask.from_fields(front_left=True,
front_right=True,
back_left=True,
back_right=True,
front_center=True,
low_frequency=True)
}.get(self.__channels__, ChannelMask(0))
elif (compression_code == 0xFFFE):
fmt.skip(128)
mask = fmt.read(32)
self.__channel_mask__ = ChannelMask(mask)
else:
from audiotools.text import ERR_WAVPACK_UNSUPPORTED_FMT
#.........这里部分代码省略.........
示例5: __init__
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
class ALACDecoder:
def __init__(self, filename):
self.reader = BitstreamReader(open(filename, "rb"), 0)
self.reader.mark()
try:
#locate the "alac" atom
#which is full of required decoding parameters
try:
stsd = self.find_sub_atom("moov", "trak", "mdia",
"minf", "stbl", "stsd")
except KeyError:
raise ValueError("required stsd atom not found")
(stsd_version, descriptions) = stsd.parse("8u 24p 32u")
(alac1,
alac2,
self.samples_per_frame,
self.bits_per_sample,
self.history_multiplier,
self.initial_history,
self.maximum_k,
self.channels,
self.sample_rate) = stsd.parse(
#ignore much of the stuff in the "high" ALAC atom
"32p 4b 6P 16p 16p 16p 4P 16p 16p 16p 16p 4P" +
#and use the attributes in the "low" ALAC atom instead
"32p 4b 4P 32u 8p 8u 8u 8u 8u 8u 16p 32p 32p 32u")
self.channel_mask = {1: 0x0004,
2: 0x0003,
3: 0x0007,
4: 0x0107,
5: 0x0037,
6: 0x003F,
7: 0x013F,
8: 0x00FF}.get(self.channels, 0)
if ((alac1 != 'alac') or (alac2 != 'alac')):
raise ValueError("Invalid alac atom")
#also locate the "mdhd" atom
#which contains the stream's length in PCM frames
self.reader.rewind()
mdhd = self.find_sub_atom("moov", "trak", "mdia", "mdhd")
(version, ) = mdhd.parse("8u 24p")
if (version == 0):
(self.total_pcm_frames,) = mdhd.parse(
"32p 32p 32p 32u 2P 16p")
elif (version == 1):
(self.total_pcm_frames,) = mdhd.parse(
"64p 64p 32p 64U 2P 16p")
else:
raise ValueError("invalid mdhd version")
#finally, set our stream to the "mdat" atom
self.reader.rewind()
(atom_size, atom_name) = self.reader.parse("32u 4b")
while (atom_name != "mdat"):
self.reader.skip_bytes(atom_size - 8)
(atom_size, atom_name) = self.reader.parse("32u 4b")
finally:
self.reader.unmark()
def find_sub_atom(self, *atom_names):
reader = self.reader
for (last, next_atom) in iter_last(iter(atom_names)):
try:
(length, stream_atom) = reader.parse("32u 4b")
while (stream_atom != next_atom):
reader.skip_bytes(length - 8)
(length, stream_atom) = reader.parse("32u 4b")
if (last):
return reader.substream(length - 8)
else:
reader = reader.substream(length - 8)
except IOError:
raise KeyError(next_atom)
def read(self, pcm_frames):
#if the stream is exhausted, return an empty pcm.FrameList object
if (self.total_pcm_frames == 0):
return from_list([], self.channels, self.bits_per_sample, True)
#otherwise, read one ALAC frameset's worth of frame data
frameset_data = []
frame_channels = self.reader.read(3) + 1
while (frame_channels != 0x8):
frameset_data.extend(self.read_frame(frame_channels))
frame_channels = self.reader.read(3) + 1
self.reader.byte_align()
#reorder the frameset to Wave order, depending on channel count
if ((self.channels == 1) or (self.channels == 2)):
pass
elif (self.channels == 3):
frameset_data = [frameset_data[1],
frameset_data[2],
#.........这里部分代码省略.........
示例6: SHNDecoder
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
class SHNDecoder(object):
def __init__(self, filename):
self.reader = BitstreamReader(open(filename, "rb"), False)
(self.file_type,
self.channels,
self.block_length,
self.max_LPC,
self.number_of_means) = self.read_header()
if ((1 <= self.file_type) and (self.file_type <= 2)):
self.bits_per_sample = 8
self.signed_samples = (self.file_type == 1)
elif ((3 <= self.file_type) and (self.file_type <= 6)):
self.bits_per_sample = 16
self.signed_samples = (self.file_type in (3, 5))
else:
raise ValueError("unsupported Shorten file type")
self.wrapped_samples = [[0] * 3 for c in range(self.channels)]
self.means = [[0] * self.number_of_means
for c in range(self.channels)]
self.left_shift = 0
self.stream_finished = False
# try to read the first command for a wave/aiff header
self.reader.mark()
self.read_metadata()
self.reader.rewind()
self.reader.unmark()
def read_metadata(self):
from io import BytesIO
command = self.unsigned(2)
if (command == 9):
# got verbatim, so read data
verbatim_bytes = ints_to_bytes([self.unsigned(8) & 0xFF
for i in range(self.unsigned(5))])
try:
wave = BitstreamReader(BytesIO(verbatim_bytes), True)
header = wave.read_bytes(12)
if (header.startswith(b"RIFF") and header.endswith(b"WAVE")):
# got RIFF/WAVE header, so parse wave blocks as needed
total_size = len(verbatim_bytes) - 12
while (total_size > 0):
(chunk_id, chunk_size) = wave.parse("4b 32u")
total_size -= 8
if (chunk_id == b'fmt '):
(channels,
self.sample_rate,
bits_per_sample,
channel_mask) = parse_fmt(
wave.substream(chunk_size))
self.channel_mask = int(channel_mask)
return
else:
if (chunk_size % 2):
wave.read_bytes(chunk_size + 1)
total_size -= (chunk_size + 1)
else:
wave.read_bytes(chunk_size)
total_size -= chunk_size
else:
# no fmt chunk, so use default metadata
pass
except (IOError, ValueError):
pass
try:
aiff = BitstreamReader(BytesIO(verbatim_bytes), False)
header = aiff.read_bytes(12)
if (header.startswith(b"FORM") and header.endswith(b"AIFF")):
# got FORM/AIFF header, so parse aiff blocks as needed
total_size = len(verbatim_bytes) - 12
while (total_size > 0):
(chunk_id, chunk_size) = aiff.parse("4b 32u")
total_size -= 8
if (chunk_id == b'COMM'):
(channels,
total_sample_frames,
bits_per_sample,
self.sample_rate,
channel_mask) = parse_comm(
aiff.substream(chunk_size))
self.channel_mask = int(channel_mask)
return
else:
if (chunk_size % 2):
aiff.read_bytes(chunk_size + 1)
total_size -= (chunk_size + 1)
else:
aiff.read_bytes(chunk_size)
total_size -= chunk_size
else:
# no COMM chunk, so use default metadata
pass
except IOError:
pass
#.........这里部分代码省略.........
示例7: AiffReader
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
#.........这里部分代码省略.........
self.sample_rate,
channel_mask) = parse_comm(self.stream)
self.channel_mask = int(channel_mask)
self.bytes_per_pcm_frame = ((self.bits_per_sample // 8) *
self.channels)
self.remaining_pcm_frames = self.total_pcm_frames
comm_chunk_read = True
elif (chunk_id == b"SSND"):
# when "SSND" chunk encountered,
# strip off the "offset" and "block_size" attributes
# and ready PCMReader for reading
if (not comm_chunk_read):
from audiotools.text import ERR_AIFF_PREMATURE_SSND_CHUNK
raise ValueError(ERR_AIFF_PREMATURE_SSND_CHUNK)
else:
self.stream.skip_bytes(8)
self.stream.mark()
return
else:
# all other chunks are ignored
self.stream.skip_bytes(chunk_size)
if (chunk_size % 2):
if (len(self.stream.read_bytes(1)) < 1):
from audiotools.text import ERR_AIFF_INVALID_CHUNK
raise ValueError(ERR_AIFF_INVALID_CHUNK)
total_size -= (chunk_size + 1)
else:
total_size -= chunk_size
else:
# raise an error if no "SSND" chunk is encountered
from audiotools.text import ERR_AIFF_NO_SSND_CHUNK
raise ValueError(ERR_AIFF_NO_SSND_CHUNK)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __del__(self):
if (self.stream.has_mark()):
self.stream.unmark()
def read(self, pcm_frames):
"""try to read a pcm.FrameList with the given number of PCM frames"""
# try to read requested PCM frames or remaining frames
requested_pcm_frames = min(max(pcm_frames, 1),
self.remaining_pcm_frames)
requested_bytes = (self.bytes_per_pcm_frame *
requested_pcm_frames)
pcm_data = self.stream.read_bytes(requested_bytes)
# raise exception if "SSND" chunk exhausted early
if (len(pcm_data) < requested_bytes):
from audiotools.text import ERR_AIFF_TRUNCATED_SSND_CHUNK
raise IOError(ERR_AIFF_TRUNCATED_SSND_CHUNK)
else:
self.remaining_pcm_frames -= requested_pcm_frames
# return parsed chunk
return FrameList(pcm_data,
self.channels,
self.bits_per_sample,
True,
True)
def read_closed(self, pcm_frames):
raise ValueError("cannot read closed stream")
def seek(self, pcm_frame_offset):
"""tries to seek to the given PCM frame offset
returns the total amount of frames actually seeked over"""
if (pcm_frame_offset < 0):
from audiotools.text import ERR_NEGATIVE_SEEK
raise ValueError(ERR_NEGATIVE_SEEK)
# ensure one doesn't walk off the end of the file
pcm_frame_offset = min(pcm_frame_offset,
self.total_pcm_frames)
# position file in "SSND" chunk
self.stream.rewind()
self.stream.seek((pcm_frame_offset * self.bytes_per_pcm_frame), 1)
self.remaining_pcm_frames = (self.total_pcm_frames -
pcm_frame_offset)
return pcm_frame_offset
def seek_closed(self, pcm_frame_offset):
raise ValueError("cannot seek closed stream")
def close(self):
"""closes the stream for reading"""
self.stream.close()
self.read = self.read_closed
self.seek = self.seek_closed
示例8: WaveReader
# 需要导入模块: from audiotools.bitstream import BitstreamReader [as 别名]
# 或者: from audiotools.bitstream.BitstreamReader import rewind [as 别名]
#.........这里部分代码省略.........
self.channels)
fmt_chunk_read = True
elif (chunk_id == b"data"):
# when "data" chunk encountered,
# use its size to determine total PCM frames
# and ready PCMReader for reading
if (not fmt_chunk_read):
from audiotools.text import ERR_WAV_PREMATURE_DATA
self.stream.close()
raise ValueError(ERR_WAV_PREMATURE_DATA)
else:
self.total_pcm_frames = (chunk_size //
self.bytes_per_pcm_frame)
self.remaining_pcm_frames = self.total_pcm_frames
self.stream.mark()
return
else:
# all other chunks are ignored
self.stream.skip_bytes(chunk_size)
if (chunk_size % 2):
if (len(self.stream.read_bytes(1)) < 1):
from audiotools.text import ERR_WAV_INVALID_CHUNK
self.stream.close()
raise ValueError(ERR_WAV_INVALID_CHUNK)
total_size -= (chunk_size + 1)
else:
total_size -= chunk_size
else:
# raise an error if no "data" chunk is encountered
from audiotools.text import ERR_WAV_NO_DATA_CHUNK
self.stream.close()
raise ValueError(ERR_WAV_NO_DATA_CHUNK)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __del__(self):
if (self.stream.has_mark()):
self.stream.unmark()
def read(self, pcm_frames):
"""try to read a pcm.FrameList with the given number of PCM frames"""
# try to read requested PCM frames or remaining frames
requested_pcm_frames = min(max(pcm_frames, 1),
self.remaining_pcm_frames)
requested_bytes = (self.bytes_per_pcm_frame *
requested_pcm_frames)
pcm_data = self.stream.read_bytes(requested_bytes)
# raise exception if "data" chunk exhausted early
if (len(pcm_data) < requested_bytes):
from audiotools.text import ERR_WAV_TRUNCATED_DATA_CHUNK
raise IOError(ERR_WAV_TRUNCATED_DATA_CHUNK)
else:
self.remaining_pcm_frames -= requested_pcm_frames
# return parsed chunk
return FrameList(pcm_data,
self.channels,
self.bits_per_sample,
False,
self.bits_per_sample != 8)
def read_closed(self, pcm_frames):
raise ValueError("cannot read closed stream")
def seek(self, pcm_frame_offset):
"""tries to seek to the given PCM frame offset
returns the total amount of frames actually seeked over"""
if (pcm_frame_offset < 0):
from audiotools.text import ERR_NEGATIVE_SEEK
raise ValueError(ERR_NEGATIVE_SEEK)
# ensure one doesn't walk off the end of the file
pcm_frame_offset = min(pcm_frame_offset, self.total_pcm_frames)
# position file in "data" chunk
self.stream.rewind()
self.stream.seek(pcm_frame_offset * self.bytes_per_pcm_frame, 1)
self.remaining_pcm_frames = (self.total_pcm_frames -
pcm_frame_offset)
return pcm_frame_offset
def seek_closed(self, pcm_frame_offset):
raise ValueError("cannot seek closed stream")
def close(self):
"""closes the stream for reading"""
self.stream.close()
self.read = self.read_closed
self.seek = self.seek_closed