예제 #1
0
def check_if_sound_is_wav(original_file):
    response = False
    # if it is a mp3 file it should return None
    if sndhdr.what(original_file):
        if sndhdr.what(original_file)[0] == 'wav':
            response = True
    return response
예제 #2
0
def test():
    import sys
    if len(sys.argv) == 2:
        print sndhdr.what(sys.argv[1])
        inaudio = getReader(sys.argv[1])
        outaudio = getdev()
    elif len(sys.argv) == 3:
        inaudio = getReader(sys.argv[1])
        outaudio = getWriter(sys.argv[2])
    while True:
        data = inaudio.read()
        outaudio.write(data)
        print "len(data)", len(data)
        if not len(data):
            print "stopping because data len == %d"%(len(data))
            break
    def set_wav(self, filepath):
        """waveファイルの読み込み
        疑似ファイル(画像等)を.wavで読み込ますと、waveパッケージの方で
        エラーを出力してしまう。ファイル拡張子のエラーに対応している。
        """
        # ファイルが存在しない場合は返却
        if not os.path.exists(filepath):
            raise StandardError("File is not exist %s" % (filepath))
            return

        # ファイル名の取得
        filename = os.path.basename(filepath)

        # wavファイルかどうかを調べる(疑似ファイルならエラー)
        if sndhdr.what(filepath)[0] is not 'wav':
            return

        # オーディオファイルであれば
        try:
            # ファイルオープン
            wf_tmp = wave.open(filepath, 'rb')
        except IOError:
            raise StandardError("Cant file load %s" % (filename))
        else:
            # 正常時の処理
            self.wf = wf_tmp
            self.filename = filename
            self.filepath = filepath
            self.__initialize()
            self.__set_data()
        finally:
            pass
예제 #4
0
    def play_sound(self, soundfile):
        import ossaudiodev
        import sndhdr

        try:
            (t, r, c, f, b) = sndhdr.what(soundfile)
        except Exception as e:
            print(f"Unable to determine sound header of {soundfile}: {e}")
            return

        if t != "wav":
            print(f"Unable to play non-wav file {soundfile}")
            return

        if b != 16:
            print(f"Unable to support strange non-16-bit audio ({b})")
            return

        dev = None
        try:
            dev = ossaudiodev.open("w")
            dev.setfmt(ossaudiodev.AFMT_S16_LE)
            dev.channels(c)
            dev.speed(r)

            f = file(soundfile, "rb")
            dev.write(f.read())
            f.close()

            dev.close()
        except Exception as e:
            print(f"Error playing sound {soundfile}: {e}")

        if dev:
            dev.close()
예제 #5
0
    def _get_file_type(self, potential_path):
        could_be_fp = False
        for char in ('/', '\\', ':\\'):
            if char in potential_path:
                could_be_fp = True

        if not could_be_fp:
            return False

        try:
            is_img = imghdr.what(potential_path)
            if is_img is None:
                return False
            else:
                return DATA_SUBTYPES.IMAGE
        except:
            # Not a file or file doesn't exist
            return False

        # @TODO: CURRENTLY DOESN'T DIFFERENTIATE BETWEEN AUDIO AND VIDEO
        is_audio = sndhdr.what(potential_path)
        if is_audio is not None:
            return DATA_SUBTYPES.AUDIO

        return False
예제 #6
0
    def set_wav(self, filepath):
        """waveファイルの読み込み
        疑似ファイル(画像等)を.wavで読み込ますと、waveパッケージの方で
        エラーを出力してしまう。ファイル拡張子のエラーに対応している。
        """
        # ファイルが存在しない場合は返却
        if not os.path.exists(filepath):
            raise StandardError("File is not exist %s" % (filepath))
            return

        # ファイル名の取得
        filename = os.path.basename(filepath)

        if sndhdr.what(filepath)[0] is not 'wav':
            return

        # オーディオファイルであれば
        try:
            # ファイルオープン
            wf_tmp = wave.open(filepath, 'rb')
        except IOError:
            raise StandardError("Cant file load %s" % (filename))
        else:
            # 正常時の処理
            self.wf = wf_tmp
            self.filename = filename
            self.filepath = filepath
            self.__initialize()
            self.__set_data()
        finally:
            pass
예제 #7
0
 def open(cls, filename, write_type = None):
   """ 
   Open an audio file. write_type is "wav" or "mp3", if
   writing. Automatically determines the file format if reading.
   """
   from wavfile import WavFile
   from mp3file import MP3File
   
   if (write_type == None):
     file_object = open(filename, "rb")
     try:
       layer = MP3(filename).info.layer
     except:
       layer = -1
     if (layer == 3):
       return MP3File(filename, False)
     elif ((sndhdr.what(filename) or [None])[0] == "wav"):
       return WavFile(filename, False)
     else:
       raise FormatError("unrecognized audio format")
       exit()
     
   else:
     if (write_type == "wav"):
       return WavFile(filename, True)
     elif (write_type == "mp3"):
       return MP3File(filename, True)
     else:
       assert False
예제 #8
0
def test():
    import sys
    if len(sys.argv) == 2:
        print sndhdr.what(sys.argv[1])
        inaudio = getReader(sys.argv[1])
        outaudio = getdev()
    elif len(sys.argv) == 3:
        inaudio = getReader(sys.argv[1])
        outaudio = getWriter(sys.argv[2])
    while True:
        data = inaudio.read()
        outaudio.write(data)
        print "len(data)", len(data)
        if not len(data):
            print "stopping because data len == %d" % (len(data))
            break
예제 #9
0
def playfile(filename):
    killchild()
    try:
        tuple = sndhdr.what(filename)
    except IOError, msg:
        print 'Can\'t open', filename, msg
        stdwin.fleep()
        return
예제 #10
0
    def is_form_correct(self, audio_file_path):

        header = sndhdr.what(audio_file_path)

        if header.filetype == 'wav' and header.nchannels == 2:
            #('FILE SUPPORTED')
            return True
        return False
예제 #11
0
 def getSoundHeader(self, infile):
     #读取语音文件的格式
     info = sndhdr.what(infile)
     txt = "语音文件: " + infile + "\n" + "Type: " + info[0] + "\n" + \
         "Sampling rate: " + str(info[1]) + "\n" + \
         "Channels: " + str(info[2]) + "\n" + \
         "Frames: " + str(info[3]) + "\n" + "Bits per sample: " + str(info[4])
     self.label.config(text = txt)
예제 #12
0
def playfile(filename):
	killchild()
	try:
		tuple = sndhdr.what(filename)
	except IOError, msg:
		print 'Can\'t open', filename, msg
		stdwin.fleep()
		return
예제 #13
0
def is_wav(fn):
    """Returns True if ``fn`` is a WAV file."""
    hinfo = sndhdr.what(fn)
    if hinfo is None:
        return False
    elif hinfo[0] != 'wav':
        return False
    return True
예제 #14
0
파일: wav.py 프로젝트: tewe/canta
 def load(self):
     try:
         opener = type_map[sndhdr.what(self.loc)]
         f = opener.open(self.loc, "rb")
         length = f.getnframes() / f.getframerate()
         self.mutagen = {'bitrate': -1, 'length': length}
     except (IOError, KeyError):
         self.mutagen = {'bitrate': -1, 'length': -1}
예제 #15
0
파일: gui_old.py 프로젝트: andyli8500/MICA
 def show_file_dialog(self):
     if (self.data_file == False):
         self.data_source = pathgetter()
         # print(self.data_source)
         if os.path.isfile(self.data_source) and (sndhdr.what(self.data_source) is not None):
             self.isValid = True
         else:
             self.isValid = False
         self.data_file = True
예제 #16
0
파일: platform.py 프로젝트: yanicky/d-rats
    def play_sound(self, soundfile):
        import ossaudiodev
        import sndhdr

        try:
            (t, r, c, f, b) = sndhdr.what(soundfile)
        except Exception, e:
            print "Unable to determine sound header of %s: %s" % (soundfile, e)
            return
예제 #17
0
    def play_sound(self, soundfile):
        import ossaudiodev
        import sndhdr

        try:
            (t, r, c, f, b) = sndhdr.what(soundfile)
        except Exception, e:
            print "Unable to determine sound header of %s: %s" % (soundfile, e)
            return
예제 #18
0
def convert(input, output):
    samplePerCycle = 1
    """Converts between wav and aiff files"""
    if sndhdr.what(input)[0] == 'wav':
        #from Wav to Aiff.
        input = wave.open(input, 'r')
        output = aifc.open(output, 'w')

    elif sndhdr.what(input)[0] == 'aiff':
        #from Aiff to Wav
        input = aifc.open(input, 'r')
        output = wave.open(output, 'w')

    nframes = input.getnframes()

    output.setnchannels(input.getnchannels())
    output.setframerate(input.getframerate())
    output.setsampwidth(input.getsampwidth())

    i = 1
    dataset = []

    #input.setpos(1)
    #dataval = input.readframes(nframes)
    #dataset.append(dataval)
    for i in range(0, nframes, samplePerCycle):
        input.setpos(i)
        dataval = input.readframes(samplePerCycle)
        dataset.append(dataval)
        if (i % 1000 == 0):
            print str(i) + "/" + str(nframes)

        #===========================================
        #Implement output(nframes) == input(nframes)
        #===========================================
        #if (nframes % samplePerCycle < samplePerCycle):
        #	if (nframes % samplePerCycle != 0):
        #		samplePerCycle = nframes % samplePerCycle

    valuestr = ''.join(dataset)
    output.writeframes(valuestr)

    input.close()
    output.close()
예제 #19
0
def convert(input, output):
	samplePerCycle = 1
	"""Converts between wav and aiff files"""
	if sndhdr.what(input)[0] == 'wav':
		#from Wav to Aiff.
		input = wave.open(input, 'r')
		output = aifc.open(output, 'w')
	
	elif sndhdr.what(input)[0] == 'aiff':
		#from Aiff to Wav
		input = aifc.open(input, 'r')
		output = wave.open(output, 'w')

	nframes = input.getnframes()
	
	output.setnchannels(input.getnchannels())
	output.setframerate(input.getframerate())
	output.setsampwidth(input.getsampwidth())
	
	i = 1
	dataset = []
	
	#input.setpos(1)
	#dataval = input.readframes(nframes)
	#dataset.append(dataval)
	for i in range(0, nframes, samplePerCycle):
		input.setpos(i)
		dataval = input.readframes(samplePerCycle)
		dataset.append(dataval)
		if(i%1000==0):
			print str(i) + "/" + str(nframes)
		
		#===========================================
		#Implement output(nframes) == input(nframes)
		#===========================================
		#if (nframes % samplePerCycle < samplePerCycle):
		#	if (nframes % samplePerCycle != 0):
		#		samplePerCycle = nframes % samplePerCycle
		
	valuestr = ''.join(dataset)
	output.writeframes(valuestr)
	
	input.close()
	output.close()
예제 #20
0
 def __init__(self, file_path):
     self._file_path = pathlib.Path(file_path)
     if not self._file_path.exists():
         raise ValueError(self._file_path)
     headers = sndhdr.what(self._file_path)
     self._frame_count = headers.nframes
     self._sample_rate = headers.framerate
     self._channel_count = headers.nchannels
     self._sample_width = headers.sampwidth
     self._file_type = headers.filetype
예제 #21
0
파일: swfback.py 프로젝트: ctz/flashover
def get_sound_meta(snf):
    hdr = sndhdr.what(snf)
    if hdr:
        tt, rate, chans, frames, bits_per_samp = hdr
        return dict(snd_type = tt, snd_rate = rate, snd_chans = chans, snd_frames = frames, snd_bits = bits_per_samp)
    
    hdr = mp3hdr.what(snf)
    if hdr:
        return hdr
    
    return dict()
예제 #22
0
 def load_image(self):
     try:
         # if os.path.isfile(self.stringpath.OUTPUT) and imghdr.what(self.stringpath.OUTPUT):
         if os.path.isfile(self.stringpath.OUTPUT) and sndhdr.what(self.stringpath.OUTPUT):
             try: self.viewer.IMAGE = image.load(self.stringpath.OUTPUT)
             except:
                 with FileIO(self.stringpath.OUTPUT) as f:
                     f.name = ''
                     self.viewer.IMAGE = image.load(f)
         else: self.viewer.IMAGE = None
     except IOError: self.viewer.IMAGE = None
예제 #23
0
    def audio_data(self):

        if self.audio.path:
            try:
                data = sndhdr.what(self.audio.path)
                data_str = 'filetype: %s, framerate: %s, nchannels: %s, nframes: %s, sampwidth: %s' % (
                    data[0], data[1], data[2], data[3], data[4])
                return data_str
            except:
                pass
        return 'None'
예제 #24
0
파일: models.py 프로젝트: khoidt/dialecta
 def audio_data(self):
   
   if self.audio.path:
     try:
       data = sndhdr.what(self.audio.path)
       data_str = 'filetype: %s, framerate: %s, nchannels: %s, nframes: %s, sampwidth: %s'%(
         data[0], data[1], data[2], data[3], data[4]
         )
       return data_str
     except:
       pass
   return 'None'
예제 #25
0
def checkformat(filename, expectedtype, expectedrate):
    """ Check that the file is in the expected format """
    if not os.path.isfile(filename):
        return False

    header = sndhdr.what(filename)
    # later: mp3 checking
    if header == None:
        return False

    ftype, rate, channels, frames, bps = header
    return ftype==expectedtype and rate==expectedrate
예제 #26
0
def load_pygame_sound(filepath):
    '''Return a pygame Sound object from the file at str filepath. If 
    that file is not a .wav or is corrupt in some way raise a TypeError.'''
    
    # Check if the file exists
    if not os.access(filepath, os.F_OK):
        raise Exception("This file does not exist.")
    
    # Check if it is a .wav file
    if sndhdr.what(filepath):
        assert sndhdr.what(filepath)[0] == 'wav', "The file is not a .wav file"
    
    # Check the compression. Wave_read.getcomptype() will raise an Error if it is
    # compressed.
    wav = wave.open(filepath, 'r')
    try:
        wav.getcomptype()
    except:
        raise TypeError("This .wav file is compressed.")
    wav.close()
    
    return pygame.mixer.Sound(filepath)
예제 #27
0
def get_file_subtype_if_exists(path):
    try:
        is_img = imghdr.what(path)
        if is_img is not None:
            return DATA_SUBTYPES.IMAGE

        # @TODO: CURRENTLY DOESN'T DIFFERENTIATE BETWEEN AUDIO AND VIDEO
        is_audio = sndhdr.what(path)
        if is_audio is not None:
            return DATA_SUBTYPES.AUDIO
    except Exception:
        # Not a file or file doesn't exist
        return None
예제 #28
0
def load_pygame_sound(filepath):
    '''Return a pygame Sound object from the file at str filepath. If 
    that file is not a .wav or is corrupt in some way raise a TypeError.'''

    # Check if the file exists
    if not os.access(filepath, os.F_OK):
        raise Exception("This file does not exist.")

    # Check if it is a .wav file
    if sndhdr.what(filepath):
        assert sndhdr.what(filepath)[0] == 'wav', "The file is not a .wav file"

    # Check the compression. Wave_read.getcomptype() will raise an Error if it is
    # compressed.
    wav = wave.open(filepath, 'r')
    try:
        wav.getcomptype()
    except:
        raise TypeError("This .wav file is compressed.")
    wav.close()

    return pygame.mixer.Sound(filepath)
예제 #29
0
def find_audio_files(wavDir, matcher=None):

    # Find all audio files in the directory
    allFiles = glob.glob(os.path.join(wavDir, '*.*'))
    audioFiles = []
    for f in allFiles:
        if matcher is not None and not fnmatch.fnmatch(f, matcher):
            continue
        chk = sndhdr.what(f)
        if chk is not None:
            audioFiles.append(f)

    return audioFiles
예제 #30
0
 def __init__(self, filename) :
     self._filename = filename
     self._sndType = sndhdr.what(filename)
     if self._sndType:
         self._sndType = self._sndType[0]
     if self._sndType in ['wav']:
         try:
             self._sound = wx.Sound(filename)    # support resources?
         except:
             self._sndType = None
     else:
         self._sndType = None
     if not self._sndType:
         raise SoundFileError, 'This is not a valid sound file'
예제 #31
0
    def get_files_with_wrong_format(dataset, expected_format=audio_format.AudioFileFormat.wav_mono_16bit_16k()):
        """ Return a list of file-idx's that don't conform the given audio format. """
        files_with_wrong_format = []

        for file in dataset.files.values():
            full_path = os.path.abspath(os.path.join(dataset.path, file.path))

            if os.path.isfile(full_path):
                result = sndhdr.what(full_path)

                if result is None or not expected_format.matches_sound_header(result):
                    files_with_wrong_format.append(file.idx)

        return files_with_wrong_format
예제 #32
0
    def get_files_empty(dataset):
        """ Return a list of file-idx's that contain no data. """
        empty_wavs = []

        for file in dataset.files.values():
            full_path = os.path.abspath(os.path.join(dataset.path, file.path))

            if os.path.isfile(full_path):
                result = sndhdr.what(full_path)

                if result is None or result.nframes <= 0:
                    empty_wavs.append(file.idx)

        return empty_wavs
예제 #33
0
    def __identify_media(self, root, file):
        """
        Identify the media.
        :param root: file's path
        :param file: Media file.
        :return: Named tuple
        """
        try:

            ftype = sndhdr.what(os.path.join(root, file))
            return ftype

        except Exception as e:
            return print(e)
예제 #34
0
def check_options(input_dir1, input_dir2, output_dir, chunk_size, usage):
    """
        Make sure the supplied options are meaningful. Separate from the 
        process_options function to curb function length.
    """

    # Check all arguments before printing usage message
    is_invalid = False

    # Check that input directories exist
    if not isdir(input_dir1):
        print("Input directory 1 does not exist")
        is_invalid = True

    if not isdir(input_dir2):
        print("Input directory 2 does not exist")
        is_invalid = True

    # Check that there are indeed wav files in input dirs 1 and 2
    for d in enumerate((input_dir1, input_dir2)):
        for f in os.listdir(d[1]):
            hdr = sndhdr.what(join(d[1], f))
            if hdr is not None:
                if hdr[0] == 'wav':
                    break
        else:
            print("No wavs in input directory " + str(d[0] + 1))
            is_invalid = True

    # Check if output directory exists. If it doesn't try to make the dir tree
    if not isdir(output_dir):
        try:
            os.makedirs(output_dir)
        except:
            traceback.print_exc(file=sys.stdout)
            is_invalid = True

    # Verify that chunk size is between 1 and 1000
    if isinstance(chunk_size, int):
        if (chunk_size < 1) or (chunk_size > 1000):
            print("Chunk size must be between 1 and 1000 (milliseconds)")
            is_invalid = True
    else:
        print("Chunk size must be an integer between 1 and 1000")
        is_invalid = True

    # If problem(s) with arguments, print usage and exit
    if is_invalid:
        print(usage)
        sys.exit(1)
예제 #35
0
 def test_data(self):
     for filename, expected in (
         ("sndhdr.8svx", ("8svx", 0, 1, 0, 8)),
         ("sndhdr.aifc", ("aifc", 44100, 2, 5, 16)),
         ("sndhdr.aiff", ("aiff", 44100, 2, 5, 16)),
         ("sndhdr.au", ("au", 44100, 2, 5.0, 16)),
         ("sndhdr.hcom", ("hcom", 22050.0, 1, -1, 8)),
         ("sndhdr.sndt", ("sndt", 44100, 1, 5, 8)),
         ("sndhdr.voc", ("voc", 0, 1, -1, 8)),
         ("sndhdr.wav", ("wav", 44100, 2, -1, 16)),
     ):
         filename = findfile(filename, subdir="sndhdrdata")
         what = sndhdr.what(filename)
         self.assertNotEqual(what, None, filename)
         self.assertSequenceEqual(what, expected)
예제 #36
0
 def test_data(self):
     for filename, expected in (
         ('sndhdr.8svx', ('8svx', 0, 1, 0, 8)),
         ('sndhdr.aifc', ('aifc', 44100, 2, 5, 16)),
         ('sndhdr.aiff', ('aiff', 44100, 2, 5, 16)),
         ('sndhdr.au', ('au', 44100, 2, 5.0, 16)),
         ('sndhdr.hcom', ('hcom', 22050.0, 1, -1, 8)),
         ('sndhdr.sndt', ('sndt', 44100, 1, 5, 8)),
         ('sndhdr.voc', ('voc', 0, 1, -1, 8)),
         ('sndhdr.wav', ('wav', 44100, 2, 5, 16)),
     ):
         filename = findfile(filename, subdir="sndhdrdata")
         what = sndhdr.what(filename)
         self.assertNotEqual(what, None, filename)
         self.assertSequenceEqual(what, expected)
예제 #37
0
 def test_data(self):
     for filename, expected in (
         ('sndhdr.8svx', ('8svx', 0, 1, 0, 8)),
         ('sndhdr.aifc', ('aifc', 44100, 2, 5, 16)),
         ('sndhdr.aiff', ('aiff', 44100, 2, 5, 16)),
         ('sndhdr.au', ('au', 44100, 2, 5.0, 16)),
         ('sndhdr.hcom', ('hcom', 22050.0, 1, -1, 8)),
         ('sndhdr.sndt', ('sndt', 44100, 1, 5, 8)),
         ('sndhdr.voc', ('voc', 0, 1, -1, 8)),
         ('sndhdr.wav', ('wav', 44100, 2, 5, 16)),
     ):
         filename = findfile(filename, subdir="sndhdrdata")
         what = sndhdr.what(filename)
         self.assertNotEqual(what, None, filename)
         self.assertSequenceEqual(what, expected)
예제 #38
0
파일: swfback.py 프로젝트: ctz/flashover
def get_sound_meta(snf):
    hdr = sndhdr.what(snf)
    if hdr:
        tt, rate, chans, frames, bits_per_samp = hdr
        return dict(snd_type=tt,
                    snd_rate=rate,
                    snd_chans=chans,
                    snd_frames=frames,
                    snd_bits=bits_per_samp)

    hdr = mp3hdr.what(snf)
    if hdr:
        return hdr

    return dict()
예제 #39
0
 def get_audio_files(directory):
     global files
     dir_audio_files = []
     for sub_path in os.listdir(directory):
         path = os.path.join(directory, sub_path)
         if os.path.isfile(path) and what(path).filetype == 'wav':
             if verbosity >= 4: print("Found audio_file", sub_path)
             dir_audio_files.append(path)
         elif recursive and os.path.isdir(path):
             if verbosity >= 4:
                 print("Found directory", os.path.abspath(path))
             get_audio_files(path)
     if verbosity >= 3 and recursive and len(dir_audio_files):
         print(
             f"Found {len(dir_audio_files)} audio files in {os.path.abspath(directory)}"
         )
     files += sorted(dir_audio_files)
예제 #40
0
def create_message(from_addr, to_addr, subject, body, attach_file):
    #メッセージをつくる
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = from_addr
    msg["To"] = to_addr
    msg.set_content(body)
    #添付ファイルを作成する。
    file = open(attach_file['path'], 'rb')
    file_read = file.read()
    #msg.add_attachment(file_read, maintype='image',subtype=imghdr.what(None,file_read),filename=attach_file['name'])
    msg.add_attachment(file_read,
                       maintype='audio',
                       subtype=sndhdr.what(file_read),
                       filename=attach_file['name'])
    file.close()

    return msg
예제 #41
0
    def set_wav(self, filepath):
        """waveファイルの読み込み
        疑似ファイル(画像等)を.wavで読み込ますと、waveパッケージの方で
        エラーを出力してしまう。ファイル拡張子のエラーに対応している。
        """
        # ファイルが存在しない場合は返却
        if not os.path.exists(filepath):
            raise StandardError("File is not exist %s" % (filepath))
            return

        # ファイル名の取得
        filename = os.path.basename(filepath)

        # wavファイルかどうかを調べる(疑似ファイルならエラー)
        if sndhdr.what(filepath)[0] is not 'wav':
            return

        # オーディオファイルであれば
        try:
            # ファイルオープン
            wf_tmp = wave.open(filepath, 'rb')
        except IOError:
            raise StandardError("Cant file load %s" % (filename))
        else:
            # 正常時の処理
            self.wf = wf_tmp
            self.filename = filename
            self.filepath = filepath

            # サンプルサイズ[byte]
            self.sampwidth = self.wf.getsampwidth()
            # チャンネル数(モノラル:1,ステレオ:2)
            self.channels = self.wf.getnchannels()
            # サンプリングレート
            self.fs = self.wf.getframerate()
            # オーディオフレーム数
            self.framsize = self.wf.getnframes()
            # self.data_rawのセット
            self.__set_data()
            # wevファイル情報の表示
            self.__printWaveInfo()
        finally:
            pass
예제 #42
0
    def set_wav(self, filepath):
        """waveファイルの読み込み
        疑似ファイル(画像等)を.wavで読み込ますと、waveパッケージの方で
        エラーを出力してしまう。ファイル拡張子のエラーに対応している。
        """
        # ファイルが存在しない場合は返却
        if not os.path.exists(filepath):
            raise StandardError("File is not exist %s" % (filepath))
            return

        # ファイル名の取得
        filename = os.path.basename(filepath)

        # wavファイルかどうかを調べる(疑似ファイルならエラー)
        if sndhdr.what(filepath)[0] is not 'wav':
            return

        # オーディオファイルであれば
        try:
            # ファイルオープン
            wf_tmp = wave.open(filepath, 'rb')
        except IOError:
            raise StandardError("Cant file load %s" % (filename))
        else:
            # 正常時の処理
            self.wf = wf_tmp
            self.filename = filename
            self.filepath = filepath

            # サンプルサイズ[byte]
            self.sampwidth = self.wf.getsampwidth()
            # チャンネル数(モノラル:1,ステレオ:2)
            self.channels = self.wf.getnchannels()
            # サンプリングレート
            self.fs = self.wf.getframerate()
            # オーディオフレーム数
            self.framsize = self.wf.getnframes()
            # self.data_rawのセット
            self.__set_data()
            # wevファイル情報の表示
            self.__printWaveInfo()
        finally:
            pass
예제 #43
0
def get_file_info_audio(file_path):
    """
    统计音频文件信息
    :param file_path: 文件路径
    :return: 文件信息
    """
    header = sndhdr.what(file_path)
    if not header:
        return {}

    rate = header.framerate * header.nchannels * header.sampwidth / 8
    return {
        "filetype": header.filetype,  # 文件类型
        "framerate": header.framerate,  # 音频文件的帧率
        "nchannels": header.nchannels,  # 通道数
        "nframes": header.nframes,  # 总帧数
        "sampwidth": header.sampwidth,  # 带宽
        "rate": rate,  # 比特率
        "length": header.nframes / header.framerate * 1000
    }
예제 #44
0
    def get_null_audio(self, instance_path, audio_list):
        """
        Return a list of the null audio files associated with an instance. 

        """

        null_audio = []
        for item in audio_list:
            if not os.path.isfile(instance_path + '/' + item):
                proc_logger.debug(
                        str(datetime.utcnow())[:-7]+ \
                        ' [WARNING] '+ \
                        'detected missing/deleted audio file - '+ \
                        instance_path.split('/')[-1]
                )
                continue
            res = sndhdr.what(instance_path + '/' + item)
            if res is None:
                null_audio.append(item)
        return null_audio
 def test_data(self):
     for filename, expected in (
         ('sndhdr.8svx', ('8svx', 0, 1, 0, 8)),
         ('sndhdr.aifc', ('aifc', 44100, 2, 5, 16)),
         ('sndhdr.aiff', ('aiff', 44100, 2, 5, 16)),
         ('sndhdr.au', ('au', 44100, 2, 5.0, 16)),
         ('sndhdr.hcom', ('hcom', 22050.0, 1, -1, 8)),
         ('sndhdr.sndt', ('sndt', 44100, 1, 5, 8)),
         ('sndhdr.voc', ('voc', 0, 1, -1, 8)),
         ('sndhdr.wav', ('wav', 44100, 2, 5, 16)),
     ):
         filename = findfile(filename, subdir="sndhdrdata")
         what = sndhdr.what(filename)
         self.assertNotEqual(what, None, filename)
         self.assertSequenceEqual(what, expected)
         self.assertEqual(what.filetype, expected[0])
         self.assertEqual(what.framerate, expected[1])
         self.assertEqual(what.nchannels, expected[2])
         self.assertEqual(what.nframes, expected[3])
         self.assertEqual(what.sampwidth, expected[4])
예제 #46
0
 def test_data(self):
     for filename, expected in (
         ('sndhdr.8svx', ('8svx', 0, 1, 0, 8)),
         ('sndhdr.aifc', ('aifc', 44100, 2, 5, 16)),
         ('sndhdr.aiff', ('aiff', 44100, 2, 5, 16)),
         ('sndhdr.au', ('au', 44100, 2, 5.0, 16)),
         ('sndhdr.hcom', ('hcom', 22050.0, 1, -1, 8)),
         ('sndhdr.sndt', ('sndt', 44100, 1, 5, 8)),
         ('sndhdr.voc', ('voc', 0, 1, -1, 8)),
         ('sndhdr.wav', ('wav', 44100, 2, 5, 16)),
     ):
         filename = findfile(filename, subdir="sndhdrdata")
         what = sndhdr.what(filename)
         self.assertNotEqual(what, None, filename)
         self.assertSequenceEqual(what, expected)
         self.assertEqual(what.filetype, expected[0])
         self.assertEqual(what.framerate, expected[1])
         self.assertEqual(what.nchannels, expected[2])
         self.assertEqual(what.nframes, expected[3])
         self.assertEqual(what.sampwidth, expected[4])
예제 #47
0
파일: audio.py 프로젝트: meng89/ipodshuffle
def get_type(path):
    file_type = None
    audio = mutagen.File(path)
    if audio:
        if "audio/mp3" in audio.mime:
            file_type = MP3
        elif "audio/mp4" in audio.mime:
            if audio.info.codec == "mp4a.40.2":  # 'aac-lc'
                file_type = AAC
            elif audio.info.codec == "alac":
                file_type = ALAC

    else:
        t = sndhdr.what(path)
        if t:
            if t[0] == "wav":
                file_type = WAV
            elif t[0] == "aiff":
                file_type = AIFF

    return file_type
예제 #48
0
  def __init__(self, element,
               level=1, pan=0, loops=1, begin=0.0, end=INF, **kwds):
    super(PyaudioPlayer, self).__init__(name='PyaudioPlayer')
    PlayerSetter.set_player(self, element,
                            level=level, pan=pan, loops=loops, begin=begin, end=end, **kwds)

    if begin > 0.0 or end != INF:
      LOGGER.error('The Python PyaudioPlayer doesn\'t support begin or end')

    from echomesh.sound import SetOutput
    if not SetOutput.OUTPUT_SET:
      SetOutput.set_output()

    try:
      what = sndhdr.what(self._filename)
    except IOError:
      raise Exception('Can\'t open file %s' % self._filename)

    if not what:
      raise Exception(UNKNOWN_FORMAT_ERROR % self._filename)
    filetype = what[0]
    handler = Util.FILE_READERS.get(filetype)
    if not handler:
      LOGGER.error("Can't understand the file type of file %s", self._filename)
      self.pause()
      return

    self._file_stream = handler.open(self._filename, 'rb')
    self._sample_width = self._file_stream.getsampwidth()

    (self._channels, self._sample_width, self._sampling_rate,
     _, _, _) = self._file_stream.getparams()
    self._dtype = Util.numpy_types()[self._sample_width]
    self._request_channels = 2 if self._pan else self._channels
    self._format = Sound.PYAUDIO().get_format_from_width(self._sample_width)
    self._samples_per_frame = self._sample_width * self._channels
    self._loop_number = 0
    Config.add_client(self)
    self.restart_sound()
예제 #49
0
  def __init__(self, element, level=1, pan=0, loops=1, **kwds):
    super(FilePlayer, self).__init__(name='FilePlayer')
    from echomesh.sound import SetOutput
    if not SetOutput.OUTPUT_SET:
      SetOutput.set_output()

    self.element = element
    self.file = kwds.pop('file')
    if kwds:
      LOGGER.error('Unused keywords %s', kwds)
    self.debug = True
    self.passthrough = (level == 1 and pan == 0)

    self.level = Expression(level, element)
    self.pan = Expression(pan, element)
    self.loops = loops

    filename = Util.DEFAULT_AUDIO_DIRECTORY.expand(self.file)
    filetype = sndhdr.what(filename)[0]
    handler = Util.FILE_READERS.get(filetype)
    if not handler:
      LOGGER.error("Can't understand the file type of file %s", filename)
      self.pause()
      return

    self.file_stream = handler.open(filename, 'rb')
    self.sample_width = self.file_stream.getsampwidth()

    (self.channels, self.sample_width, self.sampling_rate,
     _, _, _) = self.file_stream.getparams()
    self.dtype = Util.numpy_types()[self.sample_width]
    self.request_channels = 2 if self.pan else self.channels
    self.format = Sound.PYAUDIO().get_format_from_width(self.sample_width)
    self.samples_per_frame = self.sample_width * self.channels
    self.loop_number = 0
    Config.add_client(self)
    self.restart_sound()
예제 #50
0
 def PATH(self,value):
     self._path = value
     self.protect = False
     d,f = [],[]
     try: listdir = os.listdir(self._path)
     except OSError as e:
         self.protect = True
         self.folders.OUTPUT = ['..',os.path.basename(self._path)]
         if e.errno == 13:
             self.files.OUTPUT = ['','ACCESS DENIED']
         elif e.errno in (2,20):
             self.files.OUTPUT = ['','FOLDER DOES NOT EXIST']
     else:
         try:
             for i in sorted(listdir,key=lambda x: x.lower()):
                 if self.showhidden.status or not i.startswith('.'):
                     if os.path.isdir(os.path.join(self._path,i)): d.append(i)
                     elif not self.imagesonly.status: f.append(i)
                     else:
                         try:
                             # if imghdr.what(os.path.join(self._path,i)) or type(image.load(os.path.join(self._path,i))) is Surface: f.append(i)
                             if sndhdr.what(os.path.join(self._path,i)) or type(image.load(os.path.join(self._path,i))) is Surface: f.append(i)
                         except: continue
         except UnicodeDecodeError:
             self.protect = True
             self.folders.OUTPUT = ['..',os.path.basename(self._path)]
             self.files.OUTPUT = ['','IT SEEMS THAT THIS FOLDER CONTAINS','SOME MISFORMATTED FILENAMES']
         else:
             d.insert(0,'..')
             self.folders.OUTPUT = d
             self.files.OUTPUT = f
             if self.stringpath.OUTPUT != os.path.join(self._path,''):
                 self.stringpath.OUTPUT = os.path.join(self._path,'')
     if os.path.exists(self._path):
         self.mkdir.ACTIV = False
         self.mem = False if not os.access(self._path,os.W_OK) or os.path.isfile(self._path) else True
     else: self.mkdir.ACTIV = self.mem and True
예제 #51
0
		#stri = str(i)
		#strnframes = str(nframes)
		#progress =  "|| " + stri + " OF " + strnframes + " ||"
		fnframes = float(nframes)
		fi = float(i)
		fifr = fi/fnframes
		
		pbar.update(round(fifr*100))
		
	valuestr = ''.join(dataset)
	destination.writeframes(valuestr)
	print ''
	
	return 1

if sndhdr.what(FileLocation)[0] == 'wav':
	#from Wav to Aiff.
	location = wave.open(FileLocation, 'r')
	destination = wave.open(FileDestination, 'w')
	
	if convert(location,destination) == 1:
		print "|| CONVERSION SUCCESSFUL ||"
		
	else:
		print "|| CONVERSION UNSUCCESSFUL ||"
	
	destination.close()
	location.close()
	
elif sndhdr.what(FileLocation)[0] == 'aiff':
	#from Aiff to Wav
def Describe(filespec):
    print sndhdr.what(filespec)
예제 #53
0
'''
sndhdr 模块

sndhdr 模块, 可来识别不同的音频文件格式, 并提取文件内容相关信息. 

执行成功后, what 函数将返回一个由文件类型, 采样频率, 声道数, 音轨数和
每个采样点位数组成的元组. 具体含义请参考 help(sndhdr) .
'''
import sndhdr

result = sndhdr.what('samples/sample.wav')

if result:
	print('file format:', result)
else:
	print('connot identify file')

	
예제 #54
0
        print(f)

CHUNK = args.chunk
input_files = args.file  # is a list


if __name__ == '__main__':

    if not input_files:
        parser.print_help()

    for input_file in input_files:
        print('input file: {}'.format(input_file))

        try:
            file_type = sndhdr.what(input_file)[0] # sndhdr on mp3 file returns None, workaround needed. 
        except TypeError:
            print('{} is not supported'.format(input_file))
            continue

        #TODO
        # Handle case when converted file already exists
        # it will be added to play queue
        # 1) avconv will prompt for confirmation to conver file
        # The deletion below will delete the converted file
        # 2) program will try to play deleted file since it is added to queue
        if file_type != 'wav':
            converted_file = ''.join(input_file.split()[:-1]) + 'TEMP.wav'
            print("Calling avconv...")
            subprocess.check_call(['avconv', '-i', input_file, converted_file])
            max_vol = get_max_vol(converted_file, CHUNK) 
예제 #55
0
 def test_pickleable(self):
     filename = findfile('sndhdr.aifc', subdir="sndhdrdata")
     what = sndhdr.what(filename)
     dump = pickle.dumps(what)
     self.assertEqual(pickle.loads(dump), what)
예제 #56
0
파일: test_sndhdr.py 프로젝트: 10sr/cpython
 def test_pickleable(self):
     filename = findfile('sndhdr.aifc', subdir="sndhdrdata")
     what = sndhdr.what(filename)
     for proto in range(pickle.HIGHEST_PROTOCOL + 1):
         dump = pickle.dumps(what, proto)
         self.assertEqual(pickle.loads(dump), what)
예제 #57
0
import sndhdr

result = sndhdr.what("samples/sample.wav")

if result:
    print "file format:", result
else:
    print "cannot identify file"

## file format: ('wav', 44100, 1, -1, 16)
예제 #58
0
def DescribeFile(filespec):
    return sndhdr.what(filespec)
예제 #59
0
def file_is_wav(path_to_file):
    '''Check if file is wav file'''
    if sndhdr.what(path_to_file):
        return sndhdr.what(path_to_file)[0] == 'wav'
    return False