Example #1
0
 def close(self, info):
     self.counter[0] *= -1
     v = (np.array(self.data) * 32767).astype(np.int16)
     with wave.Wave_write('hoge.wav') as wf:
         wf.setnchannels(1)
         wf.setsampwidth(2)
         wf.setframerate(info['framerate'])
         wf.writeframes(v.tobytes('C'))
     v = (np.array(self.result) * 32767).astype(np.int16)
     with wave.Wave_write('result.wav') as wf:
         wf.setnchannels(1)
         wf.setsampwidth(2)
         wf.setframerate(16000)
         wf.writeframes(v.tobytes('C'))
def raw_audio2wav(raw_audio: bytes, pyaudio_config: dict) -> bytes or None:
    '''
    pyaudio_config has the next format:
    "pyaudio":{
        "format": pyaudio.<format>,
        "channels": int,
        "rate": int,
        "frames_per_buffer": int,
        "device": int
    },
    '''
    try:
        samp_size = pyaudio.PyAudio().get_sample_size(pyaudio_config['format'])
        f = io.BytesIO()
        wave_writer = wave.Wave_write(f)
        wave_writer.setnchannels(pyaudio_config['channels'])
        wave_writer.setsampwidth(samp_size)
        wave_writer.setframerate(pyaudio_config['rate'])
        wave_writer.writeframes(raw_audio)

        f.seek(0)
        return f.read()
    except Exception as e:
        ErrorLogger(__file__, e)
        return None
Example #3
0
def _wav_write(signal, wav_name, sample_rate):
    """
    ::

        Utility routine for writing wav files, use scikits.audiolab if available
    """
    if HAVE_AUDIOLAB:
        scikits.audiolab.wavwrite(signal, wav_name, sample_rate)
    else:
        signal = numpy.atleast_2d(signal)
        w = wave.Wave_write(wav_name)
        if not w:
            print("Error opening file named: ", wav_name)
            raise error.BregmanError()
        w.setparams(
            (signal.shape[0], 2, sample_rate, signal.shape[1], 'NONE', 'NONE'))
        b_signal = ''  # C-style binary string
        for i in range(signal.shape[1]):
            # transform to C-style binary string
            b_signal += wave.struct.pack('h', int(32767 * signal[0, i]))
            if signal.shape[0] > 1:
                # transform to C-style binary string
                b_signal += wave.struct.pack('h', int(32767 * signal[1, i]))
        w.writeframes(b_signal)
        w.close()
    return True
def data_export(data, file_name):
    w = wave.Wave_write(file_name)
    w.setnchannels(1)
    w.setsampwidth(2)
    w.setframerate(44100)
    w.writeframes(data)
    w.close()
def button4_clicked():
    messagebox.showinfo('FileReference Tool', u'作成ファイルは↓↓\n' + f1 + u"と" + f2)
    ##wav出力
    p = (1,2,fs,N,'NONE','not compressed') #16bit= 2byte

    fr1 = wave.Wave_write(f2)
    fr1.setparams(p)
    fr1.writeframes(data1) #byte or bumarray
    fr1.close()

    fr2 = wave.Wave_write(f1)
    fr2.setparams(p)
    fr2.writeframes(data2)
    fr2.close()

    root.quit()
Example #6
0
    def split(self, audio_data, utterance_dict, speaker, save_path):
        """
        Args:
            audio_data:
            utterance_dict: the dictionary of utterance information of each speaker
                key => utterance index
                value => [start_frame, end_frame, transcript]
            speaker:
            save_path: path to save each WAV file
        """
        for utt_index, utt_info in sorted(utterance_dict.items(),
                                          key=lambda x: x[0]):
            start_frame, end_frame = utt_info[:2]
            start_frame = int((start_frame / 100) * self.sampling_rate)
            end_frame = int((end_frame / 100) * self.sampling_rate)
            audio_data_split = audio_data[start_frame:end_frame]

            self.frame_num_dict[speaker + '_' +
                                utt_index] = audio_data_split.shape[0]

            with wave.Wave_write(
                    join(save_path,
                         speaker + '_' + str(utt_index) + ".wav")) as w:
                w.setnchannels(self.channels)
                w.setsampwidth(self.sample_size)
                w.setframerate(self.sampling_rate)
                w.writeframes(audio_data_split)
Example #7
0
def main():
    # wf = wave.open("../csv2wav0/バイオリン/output391_3009.wav" , "r" ) #inai.wav  byteの文字列で起きさ
    # fs = wf.getframerate()                          # サンプリング周波数
    # g = wf.readframes(wf.getnframes()) #getframes(オーディオフレーム:長さ) readframes最大 n 個のオーディオフレームを読み、bytes文字列で返す
    #
    # print(g[2:4])
    # a= g[2:4]
    # print(a)
    # data = np.frombuffer(a,dtype="int16")
    # print(data)
    # data = struct.pack("f",data)
    # print(data)

    name = "../csv2wav0/バイオリン/output391_3009.wav"
    wavefile = wave.open(name, "r")
    framerate = wavefile.getframerate()
    x = wavefile.readframes(wavefile.getnframes())
    x = np.frombuffer(x, dtype="int16")
    G = np.fft.fft(x)
    G1 = np.fft.ifft(G[0:int(len(G) / 2)])
    G2 = G1.real
    G3 = [c for c in G2]
    G4 = np.array(G3, dtype='int16')

    w = wave.Wave_write("output.wav")
    w.setnchannels(1)
    w.setsampwidth(2)
    w.setframerate(44100)
    w.writeframes(G4)
    w.close()
Example #8
0
def createwav(data, f0, fs):
    print("create")
    w = wave.Wave_write("./create{}.wav".format(f0))
    p = (1, 2, fs, len(data), "NONE", "not compressed")
    w.setparams(p)
    w.writeframes(data)
    w.close
Example #9
0
def _wavwrite(fd, array, framerate):
    if array.dtype == np.int16:
        sampwidth = 2
    elif array.dtype == np.int32:
        sampwidth = 4
    elif array.dtype == np.float16:
        sampwidth = 2
    elif array.dtype == np.float16:
        sampwidth = 4
    else:
        raise ValueError('Not Supported dtype {}'.format(array.dtype))

    if array.ndim == 2:
        nchannels = array.shape[1]
    elif array.ndim == 1:
        nchannels = 1
    else:
        raise ValueError('Not Supported dimension: 0 or 1, but got {}'.format(
            array.ndim))

    w = wave.Wave_write(fd)
    w.setnchannels(nchannels)
    w.setsampwidth(sampwidth)
    w.setframerate(framerate)
    w.writeframes(array.tobytes())
    w.close()
Example #10
0
def save_mch_wave(mix_wavdata,
                  output_filename,
                  sample_width=2,
                  params=None,
                  framerate=16000):
    a_wavdata = mix_wavdata.transpose()
    out_wavdata = a_wavdata.copy(order='C')
    print "# save data:", output_filename, out_wavdata.shape
    ww = wave.Wave_write(output_filename)
    if params != None:
        ww.setparams(params)
    else:
        if framerate != None:
            ww.setframerate(framerate)
        if sample_width != None:
            ww.setsampwidth(sample_width)
    if len(out_wavdata.shape) <= 1:
        ww.setnchannels(1)
    else:
        ww.setnchannels(out_wavdata.shape[1])
    ww.setnframes(out_wavdata.shape[0])
    ww.writeframes(
        array.array('h',
                    out_wavdata.astype("int16").ravel()).tostring())
    ww.close()
Example #11
0
def sin_wave(l):

    A = .1
    fs = 44100
    f0 = 440
    f1 = 880
    f2 = 1320
    t = 10
    sin_wave = 0
    fname = 'sinwave.wav'
    point = np.arange(0, fs * t)
    for s in l:
        A = 100 - abs(int(float(s[1])))
        f = int(float(s[0]))

        if A > 0 :
            A *= 0.00002
            print(A, f)
            sin_wave += A * np.sin(2 * np.pi * f * point / fs)
            #[print(s) for s in sin_wave]
    plt.plot(sin_wave[0:1000])
    plt.show()
    sin_wave = [int(x * 32767.0) for x in sin_wave]  # 16bit符号付き整数に変換

    # バイナリ化
    binwave = struct.pack("h" * len(sin_wave), *sin_wave)

    w = wave.Wave_write(fname)
    p = (1, 2, fs, len(binwave), 'NONE', 'not compressed')
    w.setparams(p)
    w.writeframes(binwave)
    w.close()
Example #12
0
def noise_detection(ntime):
    with open('hoge.wav', 'rb') as f:
        data = np.frombuffer(f.read()[44:], dtype='int16').astype(
            np.float32) / 32767
    start = int(ntime * 48000 / 1024)
    end = start + 1024 * 3
    noise_data = data[start:end]
    noise_data = analyze.resampling(noise_data, 48000, 16000)
    n_spec = sp.fft(noise_data * sp.hamming(1024))
    n_pow = sp.absolute(n_spec)**2
    start = 0
    result = []
    while True:
        end = start + 1024 * 3
        if end > len(data):
            break
        ndata = analyze.resampling(data[start:end], 48000, 16000)
        ndata = analyze.spectrum_subtraction(ndata, n_pow)
        result.extend(ndata)
        start = end
    v = (np.array(result) * 32767).astype(np.int16)
    with wave.Wave_write('result.wav') as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(16000)
        w.writeframes(v.tobytes('C'))
Example #13
0
    def __init__(self, length, filename, framerate, channels=1, dtype=int32):
        # this was so much simpler to write than ChunkedWavFile
        # really wish i learned about memmap before writing it
        if isinstance(filename, str):
            self.wavfile = open(filename, "wb+")
            self._auto_close = True
        else:
            self.wavfile = filename
            self._auto_close = False

        wav = wave.Wave_write(None)
        wav.close = lambda: None
        wav.initfp(self.wavfile)
        wav.setparams((channels, dtype_info(dtype).itemsize, framerate, length,
                       "NONE", "not compressed"))
        wav._write_header(length)
        del wav
        self.wavfile.flush()
        self.wav_memmap = mmap.mmap(self.wavfile.fileno(),
                                    length * dtype_info(dtype).itemsize,
                                    access=mmap.ACCESS_WRITE)
        self.channels = ndarray((channels, length),
                                dtype,
                                self.wav_memmap,
                                self.wavfile.tell(),
                                order="F")
        self.framerate = framerate
        self.filename = filename
Example #14
0
def bin2wav(filedata, filename, channels=1, sampwidth=2, framerate=44100, nframe=0, comptype='NONE', compname='not compressed'):
    w = wave.Wave_write(filename)
    p = (channels, sampwidth, framerate, nframe, comptype, compname)

    w.setparams(p)
    w.writeframes(filedata)
    w.close()
Example #15
0
 def save_as_wave(self, y, filename):
     max_num = 32767.0 / max(y)
     bit = [int(x * max_num) for x in y]
     waves = struct.pack("h" * len(bit), *bit)
     w = wave.Wave_write(filename)
     w.setparams((1, 2, SAMPLE_RATE, len(waves), 'NONE', 'not compressed'))
     w.writeframes(waves)
     w.close()
Example #16
0
 def split_write(self, count, N):
     w = wave.Wave_write("./wav_split/" + self.filename +
                         "{:04d}.wav".format(count))
     w.setnchannels(self.channels)
     w.setsampwidth(self.sampwidth)
     w.setframerate(self.rframe)
     w.writeframes(self.audio_data[count * N:(count + 1) * N])
     w.close()
 def _write_header(self):
     logger.debug('write header')
     wave_file = wave.Wave_write(self)
     wave_file.setnchannels(CHANNELS)
     wave_file.setsampwidth(SAMP_WIDTH)
     wave_file.setframerate(RATE)
     wave_file.writeframes(b'')
     wave_file.close()
Example #18
0
def save_wav(filename, data):
    data = data.astype(np.int16)
    w = wave.Wave_write(filename)
    w.setnchannels(1)
    w.setsampwidth(2)
    w.setframerate(16000)
    w.writeframes(data)
    w.close()
Example #19
0
def output_wav(sound, fs, fileName):
    bin_out = struct.pack("h" * len(sound), *sound)

    w = wave.Wave_write(fileName)
    params = (1, 2, fs, len(bin_out), 'NONE', 'not compressed')
    w.setparams(params)
    w.writeframes(bin_out)
    w.close()
def save_wav(data, path):
    w = wave.Wave_write(path)
    w.setnchannels(1)
    w.setsampwidth(2)
    w.setframerate(16000)
    w.writeframes(data)
    # print("mixed_data")
    # print_wave_info(w)
    w.close()
def write_wave(idx, data, sr, save_dir): # sr:サンプリング周波数
    sin_wave = [int(x * 32767.0) for x in data]
    binwave = struct.pack("h" * len(sin_wave), *sin_wave)
    wav_file_path = os.path.join(save_dir, str(idx)+'.wav')
    w = wave.Wave_write(wav_file_path)
    p = (1, 2, sr, len(binwave), 'NONE', 'not compressed')
    w.setparams(p)
    w.writeframes(binwave)
    w.close()
Example #22
0
 def write_to_file(self, all_datas):
     audio_file = io.BytesIO()
     wf = wave.Wave_write(audio_file)
     wf.setnchannels(1)
     wf.setsampwidth(2)
     wf.setframerate(16000)
     wf.writeframes(b''.join(all_datas))
     audio_file.seek(0)
     self.input_queue.put(audio_file)
Example #23
0
def create_wave(sin_wave, sample_Hz, file_name):
    sin_wave = [int(x * 32767.0) for x in sin_wave]
    wave_bin = struct.pack("h" * len(sin_wave), *sin_wave)

    w = wave.Wave_write(file_name)
    p = (1, 2, sample_Hz, len(wave_bin), 'NONE', 'not comperssed')
    w.setparams(p)
    w.writeframes(wave_bin)
    w.close
Example #24
0
def addNoise(fileWav, fileVec, noiseVec, outPath, snr=5):
    fileGain = np.sqrt(np.mean(np.square(fileVec), axis=-1))
    noiseNormed = noiseVec / np.sqrt(np.mean(np.square(noiseVec), axis=-1))
    newNoise = noiseGain(snr, sGain=fileGain) * noiseNormed
    mixed = fileVec + newNoise
    outFile = wave.Wave_write(outPath)
    outFile.setparams(fileWav.getparams())
    outFile.writeframes(array.array('h', mixed.astype(np.int16)).tobytes())
    outFile.close()
Example #25
0
    def write(self, make_backup=True):
        """
        Write the GUANO .WAV file to disk.

        :param bool make_backup:  create a backup file copy before writing changes or not (default: True);
                                  backups will be saved to a folder named `GUANO_BACKUP`
        :raises ValueError:  if this `GuanoFile` doesn't represent a valid .WAV by having
            appropriate values for `self.wav_params` (see :meth:`wave.Wave_write.setparams()`)
            and `self.wav_data` (see :meth:`wave.Wave_write.writeframes()`)
        """
        # FIXME: optionally write other unknown subchunks for redundant metadata formats

        if not self.filename:
            raise ValueError('Cannot write .WAV file without a self.filename!')
        if not self.wav_params:
            raise ValueError('Cannot write .WAV file without appropriate self.wav_params (see `wavfile.setparams()`)')
        if not self.wav_data:
            raise ValueError('Cannot write .WAV file without appropriate self.wav_data (see `wavfile.writeframes()`)')

        # prepare our metadata for a byte-wise representation
        md_bytes = self.serialize()

        # create tempfile and write our vanilla .WAV ('data' sub-chunk only)
        tempfile = NamedTemporaryFile(mode='w+b', prefix='guano_temp-', suffix='.wav', delete=False)
        if os.path.isfile(self.filename):
            shutil.copystat(self.filename, tempfile.name)

        with closing(wave.Wave_write(tempfile)) as wavfile:
            wavfile.setparams(self.wav_params)
            wavfile.writeframes(self.wav_data)

        # add the 'guan' sub-chunk after the 'data' sub-chunk
        tempfile.write(_chunkid.pack(b'guan'))
        tempfile.write(_chunksz.pack(len(md_bytes)))
        tempfile.write(md_bytes)

        # fix the RIFF file length
        total_size = tempfile.tell()
        tempfile.seek(0x04)
        tempfile.write(_chunksz.pack(total_size - 8))
        tempfile.close()

        # verify it by re-parsing the new version
        GuanoFile(tempfile.name)

        # finally overwrite the original with our new version (and optionally back up first)
        if make_backup and os.path.exists(self.filename):
            backup_dir = os.path.join(os.path.dirname(self.filename), 'GUANO_BACKUP')
            backup_file = os.path.join(backup_dir, os.path.basename(self.filename))
            if not os.path.isdir(backup_dir):
                log.debug('Creating backup dir: %s', backup_dir)
                os.mkdir(backup_dir)
            if os.path.exists(backup_file):
                os.remove(backup_file)
            os.rename(self.filename, backup_file)
        os.rename(tempfile.name, self.filename)
Example #26
0
def output_wav(sound, fileName):
  sound = [int(x * 32767.0) for x in sound]

  bin_out = struct.pack("h" * len(sound), *sound)

  w = wave.Wave_write(fileName)
  params = (1, 2, 8000, len(bin_out), 'NONE', 'not compressed')
  w.setparams(params)
  w.writeframes(bin_out)
  w.close()
Example #27
0
 def write_to_file(self, audio):
     audio_file = io.BytesIO()
     wf = wave.Wave_write(audio_file)
     wf.setnchannels(2)
     wf.setsampwidth(2)
     wf.setframerate(44100)
     wf.writeframes(audio)
     audio_file.seek(0)
     print('inserting in input_queue')
     self.input_queue.put(audio_file)
Example #28
0
def create_wave(A, f0, fs, t):
    point = np.arange(0, fs * t)
    sin_wave = A * np.sin(2 * np.pi * f0 * point / fs)
    sin_wave = [int(x * 32767.0) for x in sin_wave]
    binwave = struct.pack("h" * len(sin_wave), *sin_wave)
    w = wave.Wave_write("./doremi/Doremi{}.wav".format(f0))
    p = (1, 2, fs, len(binwave), 'NONE', 'not compressed')
    w.setparams(p)
    w.writeframes(binwave)
    w.close()
Example #29
0
def save_wave(binwaves):
    now = datetime.datetime.now()
    fname = "{0}-{1}-{2}-{3}-{4}".format(now.year,now.month,now.day,now.hour,now.minute)
    w = wave.Wave_write("{0}.wav".format(fname))
    p = (1, 2, 8000, len(binwaves), 'NONE', 'not compressed')
    w.setparams(p)
    w.writeframes(binwaves)
    w.close()

    return fname
Example #30
0
def saveFile(data, fs, bit, filename, channel=1):
    print("channel", channel)
    data = [int(v * 32767.0) for v in data]
    data = struct.pack("h" * len(data), *data)
    w = wave.Wave_write(filename + ".wav")
    w.setnchannels(channel)
    w.setsampwidth(int(bit/8))
    w.setframerate(fs)
    w.writeframes(data)
    w.close()