Exemple #1
0
def savenoise(samps: np.ndarray, nhours: int, ofn: Path, fs: int, nsec: int,
              wavapi: str):
    if not ofn:
        return

    ofn = Path(ofn).expanduser()

    f: Any

    if wavapi == "raw":
        if ofn.is_file():  # delete because we're going to append
            ofn.unlink()

        with ofn.open("a+b") as f:
            for _ in range(int(nhours * 3600 / nsec)):
                f.write(samps)

    elif wavapi == "scipy":  # pragma: no cover
        from scipy.io import wavfile

        wavfile.write(ofn, fs, samps)
    elif wavapi == "skaudio":  # pragma: no cover
        from scikits.audiolab import Format, Sndfile

        fmt = Format("flac")
        f = Sndfile(ofn, "w", fmt, 1,
                    16000)  # scikit-audio does not have context manager
        f.write_frames(samps)
        f.close()
    else:
        raise ValueError(f"I do not understand write method {wavapi}")
Exemple #2
0
    def test_basic_io(self):
        """ Check open, close and basic read/write"""
        # dirty !
        ofilename = join(TEST_DATA_DIR, 'test.wav')
        rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
        try:
            nbuff = 22050

            # Open the test file for reading
            a = Sndfile(ofilename, 'r')
            nframes = a.nframes

            # Open the copy file for writing
            format = Format('wav', 'pcm16')
            b = Sndfile(fd, 'w', format, a.channels, a.samplerate)

            # Copy the data
            for i in range(nframes / nbuff):
                tmpa = a.read_frames(nbuff)
                assert tmpa.dtype == np.float
                b.write_frames(tmpa)
            nrem = nframes % nbuff
            tmpa = a.read_frames(nrem)
            assert tmpa.dtype == np.float
            b.write_frames(tmpa)

            a.close()
            b.close()
        finally:
            close_tmp_file(rfd, cfilename)
Exemple #3
0
def steg(data1, S1, T1, data2, S2, T2, theta):
    d1count = len(data1)
    d2count = len(data2)
    expectedcount = d1count + d2count
    target_split = splitArray(data2, S2, theta)
    gap_in_s = int(numpy.floor(T1 * theta / T2))
    gap = gap_in_s * S1
    i = 0
    j = gap
    while len(target_split):
        data1[j:0] = target_split[0]
        #		print "####################################################################"
        #		print "New sample sequence: data1[", j-2, ":", j+len(target_split[0])+2, "] : ", data1[j-2:j+len(target_split[0])+2]
        j += gap + len(target_split[0])
        target_split.pop(0)

    data1[0] = T1 ^ len(data1)
    data1[1] = S2 ^ len(data1)
    data1[2] = T2 ^ len(data1)
    data1[3] = theta

    size = len(data1)
    #	print "\td1: ", d1count, "\n\td2: ", d2count, "\n\tec: ", expectedcount, "\n\tsize: ", size
    op = numpy.asarray(data1)
    format = Format('wav')
    f = Sndfile("stego_file.wav", 'w', format, 1, S1)
    f.write_frames(op)
    f.close()
    return size
Exemple #4
0
 def removeFiles(self):
     if self.logs:
         self.logs.write('removing temp file')
     start_time = time.time()
     if '.flac' in self.filename: #if flac convert to wav
         if not self.removeFile:
             if self.logs:
                 self.logs.write('file was flac: creating wav copy')
             try:
                 format = Format('wav')
                 f = Sndfile(self.localfilename+".wav", 'w', format, self.channs, self.sample_rate)
                 f.write_frames(self.original)
                 f.close()
                 os.remove(self.localfilename)
                 self.localfilename = self.localfilename+".wav"
             except:
                 if self.logs :
                     self.logs.write("Rec.py : error creating wav copy : "+self.localfilename) 
                 return False
         
     if self.removeFile:
         if self.logs:
             self.logs.write('removing tmeporary file '+self.localfilename)
         if os.path.isfile(self.localfilename):
             os.remove(self.localfilename)
         if self.logs :
             self.logs.write("Rec.py : removed temporary file:" + str(time.time() - start_time))
     
     return True
Exemple #5
0
def downsample(fs, sig):
    in_file = random_string() + ".wav"
    out_file = random_string() + ".wav"

    frame_len = fs * WINDOW_SIZE
    pad = len(sig) % frame_len
    if pad > 0:
        sig = np.append(sig, np.zeros(frame_len - pad))

    f = Sndfile(in_file, 'w',
                Format(type="wav", encoding='pcm16', endianness="file"), 1, fs)
    f.write_frames(sig)
    f.close()

    sox_in = pysox.CSoxStream(in_file)
    sox_out = pysox.CSoxStream(out_file,
                               'w',
                               pysox.CSignalInfo(SAMPLE_RATE, 1, 8),
                               fileType='wav')
    sox_chain = pysox.CEffectsChain(sox_in, sox_out)
    sox_chain.add_effect(pysox.CEffect("rate", [str(SAMPLE_RATE)]))
    sox_chain.flow_effects()
    sox_out.close()

    f = Sndfile(out_file, 'r')
    sig = f.read_frames(f.nframes)
    f.close()

    os.unlink(in_file)
    os.unlink(out_file)

    return sig
Exemple #6
0
    def _test_int_io(self, dt):
        # TODO: check if neg or pos value is the highest in abs
        rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
        try:
            # Use almost full possible range possible for the given data-type
            nb = 2**(8 * np.dtype(dt).itemsize - 3)
            fs = 22050
            nbuff = fs
            a = np.random.random_integers(-nb, nb, nbuff)
            a = a.astype(dt)

            # Open the file for writing
            format = Format('wav', _DTYPE_TO_ENC[dt])
            b = Sndfile(fd, 'w', format, 1, fs)

            b.write_frames(a)
            b.close()

            b = Sndfile(cfilename, 'r')

            read_a = b.read_frames(nbuff, dtype=dt)
            b.close()

            assert_array_equal(a, read_a)

        finally:
            close_tmp_file(rfd, cfilename)
Exemple #7
0
def save_file(device,
              sound,
              name_append=None,
              prefix=(BASE_PATH + "/../recordings/")):
    file = Sndfile(
        prefix + now_stamp() + ("__" + name_append if name_append else "") +
        ".wav", 'w', Format('wav', 'pcm16'), device.channels, device.rate)
    file.write_frames((1.0 / 32678) * sound)
    file.close()
def save_record():
    global data
    n_channels, fmt = 1, Format('flac', 'pcm16')
    caller_id = agi.get_variable("CALLERID(num)")
    file_name = 'TmpSpeechFile_' + caller_id + '.flac'
    _, temp_sound_file = mkstemp(file_name)
    flac_file = Sndfile(temp_sound_file, 'w', fmt, n_channels, SAMPLE_RATE)

    flac_file.write_frames(data)
    flac_audio = AudioSegment.from_file(temp_sound_file, "flac")
    flac_audio.export(PATH + FILE_NAME, format="mp3")
Exemple #9
0
 def __init__(self,
              fn,
              samplerate,
              filefmt='wav',
              datafmt='pcm16',
              channels=1):
     fmt = Format(filefmt, datafmt)
     self.sf = Sndfile(fn,
                       mode='w',
                       format=fmt,
                       channels=channels,
                       samplerate=samplerate)
Exemple #10
0
def create_flac_from(sound_samples):
    __console.log('prepare flac format for writing to file')
    n_channels, fmt     = 1, Format('flac', 'pcm16')
    caller_id           = get_stdn_var(stdin.CALLER_ID)
    __console.log('write to temp file')
    _, temp_sound_file  = mkstemp('TmpSpeechFile_' + caller_id + '.flac')
    __console.log('prepare sound file')
    flac_file           = Sndfile(temp_sound_file, 'w', fmt, n_channels, constants.RAW_RATE)

    flac_file.write_frames(np.array(sound_samples))
    __console.log('sound file saved')
    return temp_sound_file
Exemple #11
0
def writeAudioOutput(output, fs, f, outputTitle):
    """Writes audio output"""

    outputTitle = "test.wav"
    # Define an output audio format
    formt = Format('wav', 'float64')
    outFile = Sndfile(outputTitle, 'w', formt, 1, fs)
    outFile.write_frames(output)
    #Clean Up
    f.close()
    outFile.close()
    return
Exemple #12
0
    def __init__(self,
                 filename,
                 write=False,
                 format='wav',
                 rate=None,
                 channels=None):
        """
        Open audiofile for writing or reading

        Parameters
        ----------
        filename : mixed
            Input wav file. String if a real file, `sys.stdin` for
            standard in.
        write: boolean
            Set true for writing to a file
        rate : int
            Sample rate. Only required for writing
        channels : int
            Number of Channels. Only required for writing

        Notes
        -----

        * The data is assumed to be a numpy array of
          floats, normalized between -1 and 1.

        """
        try:
            from scikits.audiolab import Format, Sndfile
        except:
            raise RuntimeError('You must have scikits.audiolab installed')

        if filename is sys.stdin:
            filename = '-'

        if write is True and (rate is None or channels is None):
            raise ValueError('You must provide sampling rate and '
                             'number of channels for writing file.')

        if write is False:
            self.f = Sndfile(filename, 'r')

            self.channels = self.f.channels
            self.rate = self.f.samplerate

        else:
            format = Format(format)
            self.f = Sndfile(filename, 'w', format, channels, rate)

            self.channels = channels
            self.rate = rate
Exemple #13
0
def save_wav(sound, action_label, object_label):
    wav_path = '/tmp/new_wav'
    filename = os.path.join(
        wav_path,
        action_label + '-' + object_label + '-' + str(time.time()) + '.wav')
    format = Format('wav')

    print 'writing', filename, '...',

    f = Sndfile(filename, 'w', format, 1, 44100)
    f.write_frames(sound)
    f.close()
    print 'DONE'
Exemple #14
0
def main(RAW_DATA_DIR, chunk_length, slide_length):
	OUTPUT_DIR=os.path.join(RAW_DATA_DIR, "parts")
	
	if os.path.isdir(OUTPUT_DIR):
		answer = raw_input("Parts already exist.\nType y to rebuild from scratch : ")
		if answer != 'y':
			print("NOT REBUILT !")
			sys.exit()
		else:
			shutil.rmtree(OUTPUT_DIR)
	os.makedirs(OUTPUT_DIR)
	
	print RAW_DATA_DIR
	print OUTPUT_DIR

	chunk_counter = 0
	format = Format('wav')

	wav_files = glob.glob(RAW_DATA_DIR + '/*.wav')

	for filename in wav_files:
		wav_file_path = filename
		path_no_extension = re.sub(ur'\.wav$', '', filename)
		# Read wav and csv files
		wave_info = scikits.audiolab.wavread(wav_file_path)
		data_wave = wave_info[0]
		samplerate = wave_info[1]
		len_wave = len(data_wave)

		# Cut them in chunk_length seconds chunks.
		# Sliding of slide_length seconds
		# Zero padding at the end
		time_counter = 0
		start_index = 0
		while(start_index < len_wave):
			end_index = (time_counter + chunk_length) * samplerate
			if end_index > len_wave:
				chunk_wave = np.concatenate((data_wave[start_index:], np.zeros((end_index-len_wave))))
			else:
				chunk_wave = data_wave[start_index:end_index]

			time_counter += slide_length
			start_index = time_counter * samplerate

			# Write the chunks
			outwave_name = OUTPUT_DIR + '/p' + str(chunk_counter) + '.wav'
			f = Sndfile(outwave_name, 'w', format, 1, samplerate)  # 1 stands for the number of channels
			f.write_frames(chunk_wave)

			chunk_counter += 1
	return
Exemple #15
0
def convert(filename, name):
    f = Sndfile(filename, 'r')
    fs = f.samplerate
    nc = f.channels
    enc = f.encoding

    data = f.read_frames(f.nframes)

    new_name = '/home/bitnami/apps/django/django_projects/Project/sonic_bar_code/static/newfile.wav'
    format = Format('wav')
    # f = Sndfile(new_name, 'w', format, 1, fs)
    f = Sndfile(new_name, 'w', format, nc, fs)
    f.write_frames(data)
    f.close()

    return new_name
Exemple #16
0
def specgram_to_file(path,
                     mags,
                     phasifiers,
                     normalise=True,
                     specgrammode=None):
    if specgrammode == None:
        mags = np.exp(mags)
    if normalise:
        mags -= np.min(mags)
    cplx = mags * phasifiers
    pcm = istft(cplx.T)
    if normalise:
        pcm /= np.max(pcm)
    outsf = Sndfile(path, "w", Format('wav'), 1, fs)
    outsf.write_frames(pcm)
    outsf.close()
Exemple #17
0
def export_audio_vidId(fn, samplerate, vid, time, cols):
    f = [interp1d(time, cols[:, i]) for i in range(cols.shape[1])]
    fmt = Format(type=fn.split('.')[-1])

    newfn = '.'.join(
        fn.split('.')[:-2] + [fn.split('.')[-2] + ',%d' % vid] +
        [fn.split('.')[-1]])

    print 'Writing', newfn
    wav = Sndfile(newfn, 'w', fmt, cols.shape[1], samplerate)
    a = arange(samplerate) / samplerate + time[0]
    for i in xrange(int((time[-1] - time[0]))):
        y = array([g(a + i) for g in f]).T
        wav.write_frames(y)
        print '%0.2f%%     \r' % (i / (time[-1] - time[0]) * 100),
        sys.stdout.flush()
    print '100%     '
Exemple #18
0
    def test_float_frames(self):
        """ Check nframes can be a float"""
        rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
        try:
            # Open the file for writing
            format = Format('wav', 'pcm16')
            a = Sndfile(fd, 'rw', format, channels=1, samplerate=22050)
            tmp = np.random.random_integers(-100, 100, 1000)
            tmp = tmp.astype(np.short)
            a.write_frames(tmp)
            a.seek(0)
            a.sync()
            ctmp = a.read_frames(1e2, dtype=np.short)
            a.close()

        finally:
            close_tmp_file(rfd, cfilename)
Exemple #19
0
    def test_mismatch(self):
        """Check for bad arguments."""
        # This test open a file for writing, but with bad args (channels and
        # nframes inverted)
        rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
        try:
            # Open the file for writing
            format = Format('wav', 'pcm16')
            try:
                b = Sndfile(fd, 'w', format, channels=22000, samplerate=1)
                raise AssertionError("Try to open a file with more than 256 "\
                                     "channels, this should not succeed !")
            except ValueError, e:
                pass

        finally:
            close_tmp_file(rfd, cfilename)
Exemple #20
0
    def __init__(self, filename, channels=1, samplerate=44100):
        """Set defaults.

        Parameters
        ----------
        filename : str
            Name of wav file to write to.
        channels : int, optional
            Number of channels in the wav file.
        samplerate : int or float, optional
            Sample rate in Hertz.

        """
        self._format = Format('wav', encoding='pcm16')
        self._filename = filename
        self._channels = channels
        self._samplerate = samplerate
        self._sampwidth = 2
        self._fid = None
Exemple #21
0
    def __init__(
            self,
            filename,
            samplerate=44100,
            channels=1,
            format=Format('wav', 'float32'),
    ):

        self._info = {
            'filename': filename,
            'samplerate': samplerate,
            'channels': channels,
            'format': format,
            'frames': 0,
        }  # TODO: metadata not implemented

        self._sndfile = Sndfile(filename, 'w', format, channels, samplerate)
        if not self._sndfile:
            raise NameError('Sndfile error loading file %s' % filename)
Exemple #22
0
    def _test_read_write(self, dtype):
        # dirty !
        ofilename = join(TEST_DATA_DIR, 'test.wav')
        rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
        try:
            nbuff = 22050

            # Open the test file for reading
            a = Sndfile(ofilename, 'r')
            nframes = a.nframes

            # Open the copy file for writing
            format = Format('wav', _DTYPE_TO_ENC[dtype])
            b = Sndfile(fd, 'w', format, a.channels, a.samplerate)

            # Copy the data in the wav file
            for i in range(nframes / nbuff):
                tmpa = a.read_frames(nbuff, dtype=dtype)
                assert tmpa.dtype == dtype
                b.write_frames(tmpa)
            nrem = nframes % nbuff
            tmpa = a.read_frames(nrem)
            b.write_frames(tmpa)

            a.close()
            b.close()

            # Now, reopen both files in for reading, and check data are
            # the same
            a = Sndfile(ofilename, 'r')
            b = Sndfile(cfilename, 'r')
            for i in range(nframes / nbuff):
                tmpa = a.read_frames(nbuff, dtype=dtype)
                tmpb = b.read_frames(nbuff, dtype=dtype)
                assert_array_equal(tmpa, tmpb)

            a.close()
            b.close()

        finally:
            close_tmp_file(rfd, cfilename)
Exemple #23
0
def transform_wav(wav_file, output):
    filename = os.path.basename(wav_file)
    pathname = os.path.dirname(wav_file)
    speaker = os.path.basename(pathname)
    dr = os.path.basename(os.path.dirname(pathname))
    output_dir = os.path.join(output, dr, speaker)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    output_file = os.path.join(output_dir, filename)

    f = Sndfile(wav_file, 'r')
    data = f.read_frames(f.nframes)
    fs = f.samplerate
    nc = f.channels
    enc = f.encoding
    
    wav_format = Format('wav')
    f_out = Sndfile(output_file, 'w', wav_format, nc, fs)
    f_out.write_frames(data)
    f.close()
    f_out.close()
Exemple #24
0
def audiowrite(data, sr, filename):
    """
    Write audio data to a file.  Infer type from name.
    """
    stem, ext = os.path.splitext(filename)
    fmt = ext[1:]
    if fmt == "sph":
        fmt = "nist"
    format = Format(fmt)
    if len(np.shape(data)) > 1:
        nchans = np.size(data, axis=0)
    else:
        nchans = 1
    f = Sndfile(filename, 'w', format, nchans, sr)
    if np.max(np.abs(data)) >= 0.999:
        clippos = data >= 0.999
        data[clippos] = 0.999
        clipneg = data <= -0.999
        data[clipneg] = -0.999
        print "audiowrite: WARNING: %d samples clipped" % np.sum(
            np.r_[clippos, clipneg])
    f.write_frames(data)
    f.close()
Exemple #25
0
def writeresynthaudio(ch, frames, outpath, hopsize=0.5):
    "Actually resynthesises the audio and writes that out"
    audiodata = ch.resynth([frame['peaks'] for frame in frames], hopsize)
    sf = Sndfile(outpath, "w", Format(), 1, ch.sr)
    sf.write_frames(audiodata)
    sf.close()
Exemple #26
0
def save_wav(fname, signal, rate):
    fp = Sndfile(fname, 'w', Format('wav'), signal.shape[1], rate)
    fp.write_frames(signal)
    fp.close()
Exemple #27
0
    # calculate phase value
    phaseVal = np.float(i) / np.float(fs)

    # generate tone and set volume for left and right
    tone[i][0] = np.sin(2 * np.pi * freq * phaseVal) * amp
    tone[i][1] = np.sin(2 * np.pi * (freq * 2) * phaseVal) * amp

#################################################
########## WRITING TONES TO AUDIO FILE ##########
#################################################

# create a name for the new file
new_filename = 'tone.wav'

# Create a Sndfile instance for writing wav files @ 44100 Hz
format = Format('wav')
f = Sndfile(new_filename, 'w', format, 2, fs)

# Write out the samples to the file
f.write_frames(tone)

# close the audio file
f.close()

#################################################
############### PLOT USING PYLAB ################
#################################################

toneL = tone[:, 0]
toneR = tone[:, 1]
Exemple #28
0
 def test_raw(self):
     rawname = join(TEST_DATA_DIR, 'test.raw')
     format = Format('raw', 'pcm16', 'little')
     a = Sndfile(rawname, 'r', format, 1, 11025)
     assert a.nframes == 11290
     a.close()
Exemple #29
0
def decompose(inpath,
              outdir='output',
              niters=3,
              framesize=1024,
              hopsize=0.5,
              writefiles=True,
              wintype='hann'):
    """Given a path to an input file, runs a pursuit iteration to decompose the signal into atoms.
	Writes out quite a lot of files - for each iteration, partial resynth, total resynth, residual.
	Also returns the aggregated peaks and the residual."""
    if not os.path.isfile(inpath):
        raise ValueError("path %s not found" % inpath)
    sf = Sndfile(inpath, "r")
    if sf.channels != 1:
        raise Error(
            "ERROR in chirpletringmod: sound file has multiple channels (%i) - mono audio required."
            % sf.channels)

    ch = chirpletringmod.Chirpletringmod(samplerate=sf.samplerate,
                                         framesize=framesize,
                                         wintype=wintype)
    signal = sf.read_frames(sf.nframes, dtype=float32)
    sf.close()

    outnamestem = "%s/%s" % (outdir, os.path.splitext(
        os.path.basename(inpath))[0])

    resynthtot = zeros(len(signal))
    aggpeaks = []
    residual = signal
    print("chf.decompose: original signal energy %g" % sum(signal**2))
    for whichiter in range(niters):
        print("----------------------------------------")
        print("iteration %i" % whichiter)

        iterdata = ch.decompose_oneiter(residual, hopsize=hopsize)
        """Given an input signal, decomposes it a bit like one round of matching-pursuit or suchlike, with the added constraint of
		one detection per frame. Returns the peaks found, the resynthesised version, and the residual."""
        #return {'peaks':framespeaks, 'resynth':resynth, 'residual':residual}

        resynthtot += iterdata['resynth']
        aggpeaks.extend(iterdata['peaks'])

        if writefiles:
            sf = Sndfile("%s_%i_resynth.wav" % (outnamestem, whichiter), "w",
                         Format(), 1, ch.sr)
            sf.write_frames(iterdata['resynth'])
            sf.close()

            sf = Sndfile("%s_%i_resynthtot.wav" % (outnamestem, whichiter),
                         "w", Format(), 1, ch.sr)
            sf.write_frames(resynthtot)
            sf.close()

            sf = Sndfile("%s_%i_residual.wav" % (outnamestem, whichiter), "w",
                         Format(), 1, ch.sr)
            sf.write_frames(iterdata['residual'])
            sf.close()
        residual = iterdata['residual']  # fodder for next iter

        print("resynth    signal energy %g" % sum(iterdata['resynth']**2))
        print("resynthtot signal energy %g" % sum(resynthtot**2))
        print("residual   signal energy %g" % sum(residual**2))

    return {'ch': ch, 'peaks': aggpeaks, 'residual': residual}
Exemple #30
0
    def read(self, data):
        assert data.shape[1] == self.channels
        desired_read_length = data.shape[0]
        to_read_length = desired_read_length if self._readed_frames + desired_read_length <= self._info[
            'frames'] else self._info['frames'] - self._readed_frames
        tmp_data = self._sndfile.read_frames(to_read_length, dtype=data.dtype)
        for i in range(len(tmp_data)):
            data[i] = tmp_data[i]
        self._readed_frames += to_read_length
        #		print data
        return to_read_length


if __name__ == '__main__':

    with WaveWriter('lala.ogg', channels=2, format=Format('ogg',
                                                          'vorbis')) as w:
        # TODO: Metadata is not working!
        #w.metadata.title = "La casa perdida"
        #w.metadata.artist = "Me"
        data = np.zeros((512, 2), np.float32)
        for x in xrange(100):
            data[:, 0] = (x * np.arange(512, dtype=np.float32) % 512 / 512)
            data[512 - x:, 1] = 1
            data[:512 - x, 1] = -1
            w.write(data)

    import sys
    import pyaudio
    p = pyaudio.PyAudio()
    with WaveReader('MamaLadilla-TuBar.ogg', channels=2) as r:
        # open stream