本文整理汇总了Python中audiotools.bitstream.BitstreamReader类的典型用法代码示例。如果您正苦于以下问题:Python BitstreamReader类的具体用法?Python BitstreamReader怎么用?Python BitstreamReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BitstreamReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: blocks
def blocks(self, reader=None):
"""yields (length, reader) tuples of WavPack frames
length is the total length of all the substreams
reader is a BitstreamReader which can be parsed
"""
def blocks_iter(reader):
try:
while (True):
(wvpk, block_size) = reader.parse("4b 32u 192p")
if (wvpk == 'wvpk'):
yield (block_size - 24,
reader.substream(block_size - 24))
else:
return
except IOError:
return
if (reader is None):
from audiotools.bitstream import BitstreamReader
reader = BitstreamReader(open(self.filename), 1)
try:
for block in blocks_iter(reader):
yield block
finally:
reader.close()
else:
for block in blocks_iter(reader):
yield block
示例2: read
def read(cls, apefile):
"""returns an ApeTag object from an APEv2 tagged file object
may return None if the file object has no tag"""
from audiotools.bitstream import BitstreamReader
apefile.seek(-32, 2)
reader = BitstreamReader(apefile, 1)
(preamble,
version,
tag_size,
item_count,
read_only,
item_encoding,
is_header,
no_footer,
has_header) = reader.parse(cls.HEADER_FORMAT)
if ((preamble != "APETAGEX") or (version != 2000)):
return None
apefile.seek(-tag_size, 2)
return cls([ApeTagItem.parse(reader) for i in range(item_count)],
contains_header=has_header,
contains_footer=True)
示例3: parse
def parse(cls, mp3_file):
"""given an MP3 file, returns an ID3v1Comment
raises ValueError if the comment is invalid"""
from audiotools.bitstream import BitstreamReader
mp3_file.seek(-128, 2)
reader = BitstreamReader(mp3_file, 0)
(tag,
track_name,
artist_name,
album_name,
year,
comment,
track_number,
genre) = reader.parse("3b 30b 30b 30b 4b 28b 8p 1b 1b")
if (tag != 'TAG'):
raise ValueError(u"invalid ID3v1 tag")
return ID3v1Comment(track_name=track_name,
artist_name=artist_name,
album_name=album_name,
year=year,
comment=comment,
track_number=track_number,
genre=genre)
示例4: tags
def tags(file, order):
while True:
reader = BitstreamReader(file, order)
# read all the tags in an IFD
tag_count = reader.read(16)
sub_reader = reader.substream(tag_count * 12)
next_ifd = reader.read(32)
for i in range(tag_count):
(tag_code,
tag_datatype,
tag_value_count) = sub_reader.parse("16u 16u 32u")
if tag_datatype == 1: # BYTE type
tag_struct = "8u" * tag_value_count
elif tag_datatype == 3: # SHORT type
tag_struct = "16u" * tag_value_count
elif tag_datatype == 4: # LONG type
tag_struct = "32u" * tag_value_count
else: # all other types
tag_struct = "4b"
if format_size(tag_struct) <= 32:
yield (tag_code, sub_reader.parse(tag_struct))
sub_reader.skip(32 - format_size(tag_struct))
else:
offset = sub_reader.read(32)
file.seek(offset, 0)
yield (tag_code,
BitstreamReader(file, order).parse(tag_struct))
if next_ifd != 0:
file.seek(next_ifd, 0)
else:
break
示例5: __init__
def __init__(self, filename):
from audiotools.id3 import skip_id3v2_comment
AudioFile.__init__(self, filename)
try:
with open(filename, "rb") as f:
skip_id3v2_comment(f)
from audiotools.bitstream import BitstreamReader
from audiotools.text import (ERR_TTA_INVALID_SIGNATURE,
ERR_TTA_INVALID_FORMAT)
reader = BitstreamReader(f, True)
(signature,
format_,
self.__channels__,
self.__bits_per_sample__,
self.__sample_rate__,
self.__total_pcm_frames__) = reader.parse(
"4b 16u 16u 16u 32u 32u 32p")
if (signature != b"TTA1"):
raise InvalidTTA(ERR_TTA_INVALID_SIGNATURE)
elif (format_ != 1):
raise InvalidTTA(ERR_TTA_INVALID_FORMAT)
self.__total_tta_frames__ = div_ceil(
self.__total_pcm_frames__ * 245,
self.__sample_rate__ * 256)
self.__frame_lengths__ = list(reader.parse(
"%d* 32u" % (self.__total_tta_frames__) + "32p"))
except IOError as msg:
raise InvalidTTA(str(msg))
示例6: get_replay_gain
def get_replay_gain(self):
"""returns a ReplayGain object of our ReplayGain values
returns None if we have no values
may raise IOError if unable to read the file"""
from audiotools import ReplayGain
try:
rg = BitstreamReader(self.get_block(b"RG"), False)
except KeyError:
return None
version = rg.read(8)
if version != 1:
return None
gain_title = rg.read(16)
peak_title = rg.read(16)
gain_album = rg.read(16)
peak_album = rg.read(16)
if ((gain_title == 0) and (peak_title == 0) and
(gain_album == 0) and (peak_album == 0)):
return None
else:
return ReplayGain(
track_gain=64.82 - float(gain_title) / 256,
track_peak=(10 ** (float(peak_title) / 256 / 20)) / 2 ** 15,
album_gain=64.82 - float(gain_album) / 256,
album_peak=(10 ** (float(peak_album) / 256 / 20)) / 2 ** 15)
示例7: perform_lookup
def perform_lookup(disc_id,
accuraterip_server="www.accuraterip.com",
accuraterip_port=80):
"""performs web-based lookup using the given DiscID object
and returns a dict of
{track_number:[(confidence, crc, crc2), ...], ...}
where track_number starts from 1
may return a dict of empty lists if no AccurateRip entry is found
may raise urllib2.HTTPError if an error occurs querying the server
"""
from audiotools.bitstream import BitstreamReader
try:
from urllib.request import urlopen, URLError
except ImportError:
from urllib2 import urlopen, URLError
matches = {n: [] for n in disc_id.track_numbers()}
url = "http://%s:%s/accuraterip/%s/%s/%s/%s" % (accuraterip_server,
accuraterip_port,
str(disc_id)[16],
str(disc_id)[15],
str(disc_id)[14],
disc_id)
try:
response = BitstreamReader(urlopen(url), True)
except URLError:
# no CD found matching given parameters
return matches
try:
while True:
(track_count,
id1,
id2,
freedb_disc_id) = response.parse("8u 32u 32u 32u")
if (((id1 == disc_id.id1()) and
(id2 == disc_id.id2()) and
(freedb_disc_id == disc_id.freedb_disc_id()))):
for track_number in range(1, track_count + 1):
if track_number in matches:
matches[track_number].append(
tuple(response.parse("8u 32u 32u")))
except IOError:
# keep trying to parse values until the data runs out
response.close()
return matches
示例8: __read_identification__
def __read_identification__(self):
from .bitstream import BitstreamReader
f = open(self.filename, "rb")
try:
ogg_reader = BitstreamReader(f, 1)
(magic_number,
version,
header_type,
granule_position,
self.__serial_number__,
page_sequence_number,
checksum,
segment_count) = ogg_reader.parse("4b 8u 8u 64S 32u 32u 32u 8u")
if (magic_number != 'OggS'):
from .text import ERR_OGG_INVALID_MAGIC_NUMBER
raise InvalidFLAC(ERR_OGG_INVALID_MAGIC_NUMBER)
if (version != 0):
from .text import ERR_OGG_INVALID_VERSION
raise InvalidFLAC(ERR_OGG_INVALID_VERSION)
segment_length = ogg_reader.read(8)
(vorbis_type,
header,
version,
self.__channels__,
self.__sample_rate__,
maximum_bitrate,
nominal_bitrate,
minimum_bitrate,
blocksize0,
blocksize1,
framing) = ogg_reader.parse(
"8u 6b 32u 8u 32u 32u 32u 32u 4u 4u 1u")
if (vorbis_type != 1):
from .text import ERR_VORBIS_INVALID_TYPE
raise InvalidVorbis(ERR_VORBIS_INVALID_TYPE)
if (header != 'vorbis'):
from .text import ERR_VORBIS_INVALID_HEADER
raise InvalidVorbis(ERR_VORBIS_INVALID_HEADER)
if (version != 0):
from .text import ERR_VORBIS_INVALID_VERSION
raise InvalidVorbis(ERR_VORBIS_INVALID_VERSION)
if (framing != 1):
from .text import ERR_VORBIS_INVALID_FRAMING_BIT
raise InvalidVorbis(ERR_VORBIS_INVALID_FRAMING_BIT)
finally:
f.close()
示例9: get_metadata
def get_metadata(self):
"""returns a MetaData object, or None
raises IOError if unable to read the file"""
from cStringIO import StringIO
from audiotools.bitstream import BitstreamReader
from audiotools.ogg import PacketReader, PageReader
from audiotools.vorbiscomment import VorbisComment
reader = PacketReader(PageReader(open(self.filename, "rb")))
identification = reader.read_packet()
comment = BitstreamReader(StringIO(reader.read_packet()), True)
(packet_type, packet_header) = comment.parse("8u 6b")
if ((packet_type == 3) and (packet_header == 'vorbis')):
vendor_string = \
comment.read_bytes(comment.read(32)).decode('utf-8')
comment_strings = [
comment.read_bytes(comment.read(32)).decode('utf-8')
for i in xrange(comment.read(32))]
if (comment.read(1) == 1): # framing bit
return VorbisComment(comment_strings, vendor_string)
else:
return None
else:
return None
示例10: __init__
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
data_start = self.reader.getpos()
self.read_metadata()
self.reader.setpos(data_start)
示例11: __init__
def __init__(self, au_filename):
from audiotools.bitstream import BitstreamReader
from audiotools.text import (ERR_AU_INVALID_HEADER,
ERR_AU_UNSUPPORTED_FORMAT)
self.stream = BitstreamReader(open(au_filename, "rb"), False)
(magic_number,
self.data_offset,
data_size,
encoding_format,
self.sample_rate,
self.channels) = self.stream.parse("4b 5* 32u")
if magic_number != b'.snd':
self.stream.close()
raise ValueError(ERR_AU_INVALID_HEADER)
try:
self.bits_per_sample = {2: 8, 3: 16, 4: 24}[encoding_format]
except KeyError:
self.stream.close()
raise ValueError(ERR_AU_UNSUPPORTED_FORMAT)
self.channel_mask = {1: 0x4, 2: 0x3}.get(self.channels, 0)
self.bytes_per_pcm_frame = ((self.bits_per_sample // 8) *
self.channels)
self.total_pcm_frames = (data_size // self.bytes_per_pcm_frame)
self.remaining_pcm_frames = self.total_pcm_frames
示例12: __init__
def __init__(self, filename):
self.reader = BitstreamReader(open(filename, "rb"), False)
stream_start = self.reader.getpos()
# locate the "alac" atom
# which is full of required decoding parameters
try:
stsd = self.find_sub_atom(b"moov", b"trak", b"mdia",
b"minf", b"stbl", b"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 != b'alac') or (alac2 != b'alac'):
raise ValueError("Invalid alac atom")
# also locate the "mdhd" atom
# which contains the stream's length in PCM frames
self.reader.setpos(stream_start)
mdhd = self.find_sub_atom(b"moov", b"trak", b"mdia", b"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.setpos(stream_start)
(atom_size, atom_name) = self.reader.parse("32u 4b")
while atom_name != b"mdat":
self.reader.skip_bytes(atom_size - 8)
(atom_size, atom_name) = self.reader.parse("32u 4b")
示例13: __find_mp3_start__
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, False)
# skip over any bytes that aren't a valid MPEG header
pos = reader.getpos()
(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.setpos(pos)
reader.skip(8)
pos = reader.getpos()
reader.setpos(pos)
示例14: validate_footer
def validate_footer(footer, ssnd_bytes_written):
"""given a footer string as returned by aiff_header_footer()
and PCM stream parameters, returns True if the footer is valid
raises ValueError is the footer is invalid"""
from io import BytesIO
from audiotools.bitstream import BitstreamReader
total_size = len(footer)
aiff_file = BitstreamReader(BytesIO(footer), False)
try:
# ensure footer is padded properly if necessary
# based on size of data bytes written
if ssnd_bytes_written % 2:
aiff_file.skip_bytes(1)
total_size -= 1
while total_size > 0:
(chunk_id, chunk_size) = aiff_file.parse("4b 32u")
if frozenset(chunk_id).issubset(AiffAudio.PRINTABLE_ASCII):
total_size -= 8
else:
from audiotools.text import ERR_AIFF_INVALID_CHUNK
raise ValueError(ERR_AIFF_INVALID_CHUNK)
if chunk_id == b"COMM":
# ensure no COMM chunks are found
from audiotools.text import ERR_AIFF_MULTIPLE_COMM_CHUNKS
raise ValueError(ERR_AIFF_MULTIPLE_COMM_CHUNKS)
elif chunk_id == b"SSND":
# ensure no SSND chunks are found
from audiotools.text import ERR_AIFF_MULTIPLE_SSND_CHUNKS
raise ValueError(ERR_AIFF_MULTIPLE_SSND_CHUNKS)
else:
# skip the full contents of non-audio chunks
if chunk_size % 2:
aiff_file.skip_bytes(chunk_size + 1)
total_size -= (chunk_size + 1)
else:
aiff_file.skip_bytes(chunk_size)
total_size -= chunk_size
else:
return True
except IOError:
from audiotools.text import ERR_AIFF_FOOTER_IOERROR
raise ValueError(ERR_AIFF_FOOTER_IOERROR)
示例15: validate_footer
def validate_footer(footer, data_bytes_written):
"""given a footer string as returned by wave_header_footer()
and PCM stream parameters, returns True if the footer is valid
raises ValueError if the footer is invalid"""
from io import BytesIO
from audiotools.bitstream import BitstreamReader
total_size = len(footer)
wave_file = BitstreamReader(BytesIO(footer), True)
try:
# ensure footer is padded properly if necessary
# based on size of data bytes written
if data_bytes_written % 2:
wave_file.skip_bytes(1)
total_size -= 1
while total_size > 0:
(chunk_id, chunk_size) = wave_file.parse("4b 32u")
if not frozenset(chunk_id).issubset(WaveAudio.PRINTABLE_ASCII):
from audiotools.text import ERR_WAV_INVALID_CHUNK
raise ValueError(ERR_WAV_INVALID_CHUNK)
else:
total_size -= 8
if chunk_id == b"fmt ":
# ensure no fmt chunks are found
from audiotools.text import ERR_WAV_MULTIPLE_FMT
raise ValueError(ERR_WAV_MULTIPLE_FMT)
elif chunk_id == b"data":
# ensure no data chunks are found
from audiotools.text import ERR_WAV_MULTIPLE_DATA
raise ValueError(ERR_WAV_MULTIPLE_DATA)
else:
# skip the full contents of non-audio chunks
if chunk_size % 2:
wave_file.skip_bytes(chunk_size + 1)
total_size -= (chunk_size + 1)
else:
wave_file.skip_bytes(chunk_size)
total_size -= chunk_size
else:
return True
except IOError:
from audiotools.text import ERR_WAV_FOOTER_IOERROR
raise ValueError(ERR_WAV_FOOTER_IOERROR)