Beispiel #1
0
def _toaiff(filename, temps):
    if filename[-2:] == '.Z':
        (fd, fname) = tempfile.mkstemp()
        os.close(fd)
        temps.append(fname)
        sts = uncompress.copy(filename, fname)
        if sts:
            raise error(filename + ': uncompress failed')
    else:
        fname = filename
    try:
        ftype = sndhdr.whathdr(fname)
        if ftype:
            ftype = ftype[0] # All we're interested in
    except IOError as msg:
        if isinstance(msg, type(())) and len(msg) == 2 and \
                isinstance(msg[0], type(0)) and isinstance(msg[1], type('')):
            msg = msg[1]
        if not isinstance(msg, type('')):
            msg = repr(msg)
        raise error(filename + ': ' + msg)
    if ftype == 'aiff':
        return fname
    if ftype is None or not ftype in table:
        raise error('%s: unsupported audio file type %r' % (filename, ftype))
    (fd, temp) = tempfile.mkstemp()
    os.close(fd)
    temps.append(temp)
    sts = table[ftype].copy(fname, temp)
    if sts:
        raise error(filename + ': conversion to aiff failed')
    return temp
Beispiel #2
0
def _toaiff(filename, temps):
    if filename[-2:] == '.Z':
        fd, fname = tempfile.mkstemp()
        os.close(fd)
        temps.append(fname)
        sts = uncompress.copy(filename, fname)
        if sts:
            raise error, filename + ': uncompress failed'
    else:
        fname = filename
    try:
        ftype = sndhdr.whathdr(fname)
        if ftype:
            ftype = ftype[0]
    except IOError as msg:
        if type(msg) == type(()) and len(msg) == 2 and type(
                msg[0]) == type(0) and type(msg[1]) == type(''):
            msg = msg[1]
        if type(msg) != type(''):
            msg = repr(msg)
        raise error, filename + ': ' + msg

    if ftype == 'aiff':
        return fname
    else:
        if ftype is None or ftype not in table:
            raise error, '%s: unsupported audio file type %r' % (filename,
                                                                 ftype)
        fd, temp = tempfile.mkstemp()
        os.close(fd)
        temps.append(temp)
        sts = table[ftype].copy(fname, temp)
        if sts:
            raise error, filename + ': conversion to aiff failed'
        return temp
Beispiel #3
0
def _toaiff(filename, temps):
    if filename[-2:] == '.Z':
        fname = tempfile.mktemp()
        temps.append(fname)
        sts = uncompress.copy(filename, fname)
        if sts:
            raise error, filename + ': uncomress failed'
    else:
        fname = filename
    try:
        ftype = sndhdr.whathdr(fname)
        if ftype:
            ftype = ftype[0]  # All we're interested in
    except IOError:
        if type(msg) == type(()) and len(msg) == 2 and \
         type(msg[0]) == type(0) and type(msg[1]) == type(''):
            msg = msg[1]
        if type(msg) <> type(''):
            msg = ` msg `
        raise error, filename + ': ' + msg
    if ftype == 'aiff':
        return fname
    if ftype == None or not table.has_key(ftype):
        raise error, \
         filename + ': unsupported audio file type ' + `ftype`
    temp = tempfile.mktemp()
    temps.append(temp)
    sts = table[ftype].copy(fname, temp)
    if sts:
        raise error, filename + ': conversion to aiff failed'
    return temp
Beispiel #4
0
def _toaiff(filename, temps):
	if filename[-2:] == '.Z':
		fname = tempfile.mktemp()
		temps.append(fname)
		sts = uncompress.copy(filename, fname)
		if sts:
			raise error, filename + ': uncomress failed'
	else:
		fname = filename
	try:
		ftype = sndhdr.whathdr(fname)
		if ftype:
			ftype = ftype[0] # All we're interested in
	except IOError:
		if type(msg) == type(()) and len(msg) == 2 and \
			type(msg[0]) == type(0) and type(msg[1]) == type(''):
			msg = msg[1]
		if type(msg) <> type(''):
			msg = `msg`
		raise error, filename + ': ' + msg
	if ftype == 'aiff':
		return fname
	if ftype == None or not table.has_key(ftype):
		raise error, \
			filename + ': unsupported audio file type ' + `ftype`
	temp = tempfile.mktemp()
	temps.append(temp)
	sts = table[ftype].copy(fname, temp)
	if sts:
		raise error, filename + ': conversion to aiff failed'
	return temp
Beispiel #5
0
def _toaiff(filename, temps):
    if filename[-2:] == '.Z':
        fd, fname = tempfile.mkstemp()
        os.close(fd)
        temps.append(fname)
        sts = uncompress.copy(filename, fname)
        if sts:
            raise error, filename + ': uncompress failed'
    else:
        fname = filename
    try:
        ftype = sndhdr.whathdr(fname)
        if ftype:
            ftype = ftype[0]
    except IOError as msg:
        if type(msg) == type(()) and len(msg) == 2 and type(msg[0]) == type(0) and type(msg[1]) == type(''):
            msg = msg[1]
        if type(msg) != type(''):
            msg = repr(msg)
        raise error, filename + ': ' + msg

    if ftype == 'aiff':
        return fname
    else:
        if ftype is None or ftype not in table:
            raise error, '%s: unsupported audio file type %r' % (filename, ftype)
        fd, temp = tempfile.mkstemp()
        os.close(fd)
        temps.append(temp)
        sts = table[ftype].copy(fname, temp)
        if sts:
            raise error, filename + ': conversion to aiff failed'
        return temp
Beispiel #6
0
    def _validate(self):
        """ Determines whether the file is a valid wave file. Should not be called from outside the class. """
        self.valid = False
        header = sndhdr.whathdr(self.wave_file)

        if header is not None:
            if header.filetype is "wav":
                self.valid = True
Beispiel #7
0
    def _is_parameters_ok(self):
        """
        Check if received parameters are ok to perform operations in the neuron
        :return: true if parameters are ok, raise an exception otherwise

        .. raises:: MissingParameterException
        """
        if self.filename is None:
            raise MissingParameterException("You must specify (at least one) filename")
        if not isinstance(self.filename, list):
            self.filename = [self.filename]
        self.filename[:] = [x for x in self.filename if os.path.isfile(x)]
        self.filename[:] = [x for x in self.filename if sndhdr.whathdr(x) is not None]
        self.filename[:] = [x for x in self.filename if sndhdr.whathdr(x).filetype == 'wav']
        if len(self.filename) == 0:
            raise InvalidParameterException("You must specify at least one valid wav file (none remained after validation)")
        self.filename = random.choice(self.filename)
        return True
Beispiel #8
0
def _toaiff(filename, temps):
    if filename[-2:] == ".Z":
        fname = tempfile.mktemp()
        temps.append(fname)
        sts = uncompress.copy(filename, fname)
        if sts:
            raise error, filename + ": uncompress failed"
    else:
        fname = filename
    try:
        ftype = sndhdr.whathdr(fname)
        if ftype:
            ftype = ftype[0]  # All we're interested in
    except IOError, msg:
        if type(msg) == type(()) and len(msg) == 2 and type(msg[0]) == type(0) and type(msg[1]) == type(""):
            msg = msg[1]
        if type(msg) != type(""):
            msg = ` msg `
        raise error, filename + ": " + msg
Beispiel #9
0
def _toaiff(filename, temps):
    if filename[-2:] == '.Z':
        fname = tempfile.mktemp()
        temps.append(fname)
        sts = uncompress.copy(filename, fname)
        if sts:
            raise error, filename + ': uncompress failed'
    else:
        fname = filename
    try:
        ftype = sndhdr.whathdr(fname)
        if ftype:
            ftype = ftype[0]  # All we're interested in
    except IOError, msg:
        if type(msg) == type(()) and len(msg) == 2 and \
                type(msg[0]) == type(0) and type(msg[1]) == type(''):
            msg = msg[1]
        if type(msg) != type(''):
            msg = ` msg `
        raise error, filename + ': ' + msg
Beispiel #10
0
def _toaiff(filename, temps):
    if filename[-2:] == '.Z':
        (fd, fname) = tempfile.mkstemp()
        os.close(fd)
        temps.append(fname)
        sts = uncompress.copy(filename, fname)
        if sts:
            raise error, filename + ': uncompress failed'
    else:
        fname = filename
    try:
        ftype = sndhdr.whathdr(fname)
        if ftype:
            ftype = ftype[0] # All we're interested in
    except IOError, msg:
        if type(msg) == type(()) and len(msg) == 2 and \
                type(msg[0]) == type(0) and type(msg[1]) == type(''):
            msg = msg[1]
        if type(msg) != type(''):
            msg = repr(msg)
        raise error, filename + ': ' + msg
Beispiel #11
0
 def convert_to_wav(file_path):
     """
     PyAudio, AlsaPlayer, sounddevices only support wav files.
     Other files must be converted to a wav in order to be played
     This function uses ffmpeg (which must be installed) for
     conversion; python core lib sndhdr is used to check if the
     provided file is already in wav format (skips conversion).
     :param file_path: the file path to convert to wav
     """
     filetype = sndhdr.whathdr(file_path)
     if filetype is None or filetype.filetype != 'wav':
         logger.debug("[PlayerModule] Converting file to wav file: %s" % file_path)
         fnull = open(os.devnull, 'w')
         # temp file
         tmp_file_wav = file_path+ ".wav"
         # Convert file to wave
         subprocess.call(['ffmpeg', '-y', '-i', file_path, tmp_file_wav],
                         stdout=fnull, stderr=fnull)
         # remove the original file
         FileManager.remove_file(file_path)
         # rename the temp file with the same name as the original file
         os.rename(tmp_file_wav, file_path)
Beispiel #12
0
"""Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format).
Beispiel #13
0
 def update_event(self, inp=-1):
     self.set_output_val(0, sndhdr.whathdr(self.input(0)))
Beispiel #14
0
def ripread(track, offset=0):
    "rip one track from an image file."
    data = {}
    start_time = time.time()
    pid, master_fd = pty.fork()  # this could also be done with a pipe, anyone?
    if pid == CHILD:
        # debug:
        # so=open("/tmp/stdout", "w")
        # sys.stdout = so
        # se=open("/tmp/stderr", "w+")
        # sys.stderr = se
        default_signals()

        # FIXME: all this offset stuff has to go, track 0 support has to come.

        print ":fAE: waiting for status report..."
        sys.stdout.flush()
        hdr = sndhdr.whathdr(cf['_image_file'])
        my_swap_byteorder = cf['_swap_byteorder']
        my_offset = offset
        if hdr:

            # I guess most people use cdparanoia 1- (instead of 0- if applicable)
            # for image creation, so for a wav file use:

            image_offset = -offset

        else:
            if string.upper(cf['_image_file'])[-4:] == ".CDR":
                hdr = ('cdr', 44100, 2, -1, 16)  # Unknown header, assuming cdr

                # assume old cdrdao which started at track 1, not at block 0
                image_offset = -offset

            elif string.upper(cf['_image_file'])[-4:] == ".BIN":
                hdr = ('bin', 44100, 2, -1, 16)  # Unknown header, assuming bin

                # assume new cdrdao which starts at block 0, byteorder is reversed.
                my_swap_byteorder = not my_swap_byteorder
                image_offset = 0

            elif string.upper(cf['_image_file'])[-4:] == ".RAW":
                hdr = ('bin', 44100, 2, -1, 16)  # Unknown header, assuming raw
                image_offset = 0

            else:
                debug("unsupported image file " + cf['_image_file'])
                posix._exit(4)

        expected_filesize = jack.functions.tracksize(
            jack.ripstuff.all_tracks)[CDR] + CDDA_BLOCKSIZE * offset

        # WAVE header is 44 Bytes for normal PCM files...
        if hdr[0] == 'wav':
            expected_filesize = expected_filesize + 44

        if abs(jack.utils.filesize(cf['_image_file']) -
               expected_filesize) > CDDA_BLOCKSIZE:
            # we *do* allow a difference of one frame
            debug("image file size mismatch, aborted. %d != %d" %
                  (jack.utils.filesize(cf['_image_file']), expected_filesize))
            posix._exit(1)

        elif hdr[0] == 'wav' and (hdr[1], hdr[2], hdr[4]) != (44100, 2, 16):
            debug("unsupported WAV, need CDDA_fmt, aborted.")
            posix._exit(2)

        elif hdr[0] not in ('wav', 'cdr', 'bin'):
            debug("unsupported: " + hdr[0] + ", aborted.")
            posix._exit(3)

        else:
            f = open(cf['_image_file'], 'r')

            # set up output wav file:

            wav = wave.open(track[NAME] + ".wav", 'w')
            wav.setnchannels(2)
            wav.setsampwidth(2)
            wav.setframerate(44100)
            wav.setnframes(0)
            wav.setcomptype('NONE', 'not compressed')

            # calculate (and seek to) position in image file

            track_start = (track[START] + image_offset) * CDDA_BLOCKSIZE
            if hdr[0] == 'wav':
                track_start = track_start + 44
            f.seek(track_start)

            # copy / convert the stuff

            for i in range(0, track[LEN]):
                buf = array.array("h")
                buf.fromfile(f, 1176)  # CDDA_BLOCKSIZE / 2
                if not my_swap_byteorder:  # this is inverted as WAVE swabs them anyway.
                    buf.byteswap()
                wav.writeframesraw(buf.tostring())
                if i % 1000 == 0:
                    print ":fAE: Block " + ` i ` + "/" + ` track[LEN] ` + (
                        " (%2i%%)" % (i * 100 / track[LEN]))
                    sys.stdout.flush()
            wav.close()
            f.close()

            stop_time = time.time()
            read_speed = track[LEN] / CDDA_BLOCKS_PER_SECOND / (stop_time -
                                                                start_time)
            if read_speed < 100:
                print "[%2.0fx]" % read_speed,
            else:
                print "[99x]",
            if hdr[0] in ('bin', 'wav'):
                print "[      - read from image -     ]"
            else:
                print "[cdr-WARNING, check byteorder !]"
            sys.stdout.flush()
            posix._exit(0)
    else:
        # we are not the child
        data['start_time'] = start_time
        data['pid'] = pid
        data['fd'] = master_fd
        data['file'] = os.fdopen(master_fd)
        data['cmd'] = ""
        data['buf'] = ""
        data['type'] = "image_reader"
        data['prog'] = "builtin"
        data['track'] = track
        data['percent'] = 0
        data['otf'] = 0
        data['elapsed'] = 0
    return data
Beispiel #15
0
def guesstoc(names):
    "Return track list based on guessed lengths"
    num = 1
    start = 0
    erg = []
    progr = []
    for i in names:
        i_name, i_ext = os.path.splitext(os.path.basename(i))
        i_ext = i_ext.upper()
        # erg: NUM, LEN, START, COPY, PRE, CH, RIP, RATE, NAME
        if i_ext == ".MP3":
            x = jack_mp3.mp3format(i)
            if not x:
                error("could not get MP3 info for file \"%x\"" % i)
            blocks = int(x['length'] * CDDA_BLOCKS_PER_SECOND + 0.5)
            erg.append([num, blocks, start, 0, 0, 2, 1, x['bitrate'], i_name])
            progr.append(
                [num, "dae", "  *   [          simulated           ]"])
            progr.append([
                num, "enc", ` x['bitrate'] `,
                "[ s i m u l a t e d %3ikbit]" % (x['bitrate'] + 0.5)
            ])
        elif i_ext == ".WAV":
            x = sndhdr.whathdr(i)
            if not x:
                error("this is not WAV-format: " + i)
            if x != ('wav', 44100, 2, -1, 16):
                error("unsupportet format " + ` x ` + " in " + i)
            blocks = jack_utils.filesize(i)
            blocks = blocks - 44  # substract WAV header
            extra_bytes = blocks % CDDA_BLOCKSIZE
            if not extra_bytes == 0:
                warning("this is not CDDA block-aligned: " + ` i `)
                yes = raw_input(
                    "May I strip %d bytes (= %.4fseconds) off the end? " %
                    (extra_bytes, extra_bytes / 2352.0 / 75.0))
                if not string.upper((yes + "x")[0]) == "Y":
                    print "Sorry, I can't process non-aligned files (yet). Bye!"
                    sys.exit()
                f = open(i, "r+")
                f.seek(-extra_bytes, 2)
                f.truncate()
                f.close()
                blocks = blocks - extra_bytes
            blocks = blocks / CDDA_BLOCKSIZE
            erg.append(
                [num, blocks, start, 0, 0, 2, 1, cf['_bitrate'], i_name])
            progr.append(
                [num, "dae", "  =p  [  s  i  m  u  l  a  t  e  d   ]"])
        elif i_ext == ".OGG":
            if ogg:
                x = ogg.vorbis.VorbisFile(i)
                blocks = int(x.time_total(0) * CDDA_BLOCKS_PER_SECOND + 0.5)
                bitrate = temp_rate = int(
                    x.raw_total(0) * 8 / x.time_total(0) / 1000 + 0.5)
                erg.append([num, blocks, start, 0, 0, 2, 1, bitrate, i_name])
                progr.append(
                    [num, "dae", "  *   [          simulated           ]"])
                progr.append([
                    num, "enc", ` bitrate `,
                    "[ s i m u l a t e d %3ikbit]" % bitrate
                ])
            else:
                error("The OGG Python bindings are not installed.")
        elif i_ext == ".FLAC":
            if flac:
                # TODO: move all of this duplicate code (see update_progress in
                # jack_prepare.py) into a jack_flac or jack_audio or jack_formats.
                # The same goes for the OGG stuff above
                f = flac.FLAC(i)
                size = os.path.getsize(i)
                if f.info and size:
                    blocks = int(
                        float(f.info.total_samples) / f.info.sample_rate *
                        CDDA_BLOCKS_PER_SECOND + 0.5)
                    bitrate = int(size * 8 * f.info.sample_rate /
                                  f.info.total_samples / 1000)
                else:
                    blocks = bitrate = 0
                erg.append([num, blocks, start, 0, 0, 2, 1, bitrate, i_name])
                progr.append(
                    [num, "dae", "  *   [          simulated           ]"])
                progr.append([
                    num, "enc", ` bitrate `,
                    "[ s i m u l a t e d %3ikbit]" % bitrate
                ])
            else:
                error("The FLAC Python bindings are not installed.")
        else:
            error("don't know how to handle %s files." % i_ext)
        if cf['_name'] % num != i_name:
            progr.append([
                num, "ren", cf['_name'] % num + "-->" +
                unicode(i_name, cf['_charset'], "replace")
            ])
        num = num + 1
        start = start + blocks
    for i in progr:  # this is deferred so that it is only written if no
        # files fail
        progress(i)
    return erg
Beispiel #16
0
import afl
import sndhdr
import sys

while afl.loop():
    sndhdr.what(sys.argv[1])
    sndhdr.whathdr(sys.argv[1])
Beispiel #17
0
#sndhdr --- 推测声音文件的类型  https://docs.python.org/zh-cn/3/library/sndhdr.html#module-sndhdr
import sndhdr

print(
    sndhdr.what(
        "E:/linux/emacs-26.3-x86_64/lib/python2.7/test/audiodata/pluck-pcm8.wav"
    ))

print(
    sndhdr.whathdr(
        "E:/linux/emacs-26.3-x86_64/lib/python2.7/test/audiodata/pluck-pcm8.wav"
    ))