Exemplo n.º 1
0
def start():

    print('=== 现在开始录音 ===')

    # Recording duration
    duration = 10

    # Start recorder with the given values
    # of duration and sample frequency
    recording = sd.rec(int(duration * freq), samplerate=freq, channels=1)

    # Record audio for the given number of seconds
    sd.wait()

    # This will convert the NumPy array to an audio
    # file with the given sampling frequency
    # write("recording0.wav", freq, recording)

    # Convert the NumPy array to audio file
    wv.write("test_in.wav", recording, freq, sampwidth=2)

    print('=== 现在结束录音 ===')

    os.system("python connect_api.py > out.txt")

    os.system("python print_accuracy.py")
Exemplo n.º 2
0
    def process_single_file(self, file_name):
        mixture, _ = load(os.path.join(self.input_dir, file_name + '.wav'),
                          sr=self.samplerate_hz)
        speaker_signals = self.separate_single_mixture(mixture)

        write_wav(os.path.join(self.output_dir, 's1', file_name + '.wav'), \
                  speaker_signals[0, :], self.samplerate_hz, norm=True)
        wav, _ = np.array(
            librosa.load(
                os.path.join(self.output_dir, 's1', file_name + '.wav'),
                22050))
        wavio.write(os.path.join(self.output_dir, 's1', file_name + '.wav'),
                    wav,
                    22050,
                    sampwidth=3)
        write_wav(os.path.join(self.output_dir, 's2', file_name + '.wav'), \
                  speaker_signals[1, :], self.samplerate_hz, norm=True)
        wav, _ = np.array(
            librosa.load(
                os.path.join(self.output_dir, 's2', file_name + '.wav'),
                22050))
        wavio.write(os.path.join(self.output_dir, 's2', file_name + '.wav'),
                    wav,
                    22050,
                    sampwidth=3)
Exemplo n.º 3
0
def major_scale(A4=440, waveform='square', mode='fixed'):
    '''
    Simple demo playing the major scale, given the root note.
    '''
    # You can use fixed frequencies, or calculate the
    # corresponding ones for each note/tone.
    if mode == 'fixed':
        C_major = [
            261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25
        ]
    elif mode == "dynamic":
        # A tool for calculating a note's frequency is now implemented.
        # Include this functionality here.
        pass
    else:
        print('Mode not supported')
        sys.exit()

    if waveform == 'square':
        generator = SquareGenerator(duration=1)
    elif waveform == 'saw':
        generator = SawGenerator(duration=1)
    else:
        print('Waveform generator not supported.')
        sys.exit()

    scale = []
    for frequency in C_major:
        scale = np.concatenate((scale, generator.generate(frequency)), axis=0)
    wavio.write('generated_demos/c_major_scale_' + waveform + '.wav',
                scale,
                generator.rate,
                sampwidth=SAMPWIDTH)
Exemplo n.º 4
0
def record_and_recognize_song():
    print("Listening!")
    # arduino.write(bytes("Listening", 'utf-8'))
    fs = 44100  # Sample rate
    seconds = 5  # Duration of recording

    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1)

    sd.wait()  # Wait until recording is finished
    write('output1.wav', fs, myrecording)  # Save as WAV file
    wavio.write("myfile1.wav", myrecording, fs, sampwidth=2)
    sound = AudioSegment.from_wav('myfile1.wav')
    sound.export('myfile.mp3', format='mp3')
    mp3_file_content_to_recognize = open('myfile.mp3', 'rb').read()

    shazam = Shazam(mp3_file_content_to_recognize)
    recognize_generator = shazam.recognizeSong()
    song = None
    while song is None:
        song = next(recognize_generator)
    print(song)
    title = song[1]['track']['title']
    artist = song[1]['track']['subtitle']
    print(artist, title)
    os.remove("myfile.mp3")
    os.remove("myfile1.wav")
    os.remove("output1.wav")
    return artist, title
Exemplo n.º 5
0
    def save(self, wav_file: Path = "SpectroGraphic.wav"):
        """saves the spectrographic to a .wav file

        We use the wavio module
        """

        wavio.write(wav_file, self.sound_array, self.SAMPLE_RATE)
Exemplo n.º 6
0
def main():

    y1, s1 = librosa.load("audio1.wav")
    y2, s2 = librosa.load("audio2.wav")  # might need FFMPEG for this!!!

    plt.plot(y1)
    plt.show()
    length = len(y1)/s1

    plt.plot(y1)
    plt.xlim((0.5/length)*len(y1), (1/length)*len(y1))
    plt.show()

    interval = 100  # ms

    #  create a sum of 2 signals
    if len(y2) < len(y1):
        y3 = y1.copy()
        y3[:len(y2)] += y2
    else:
        y3 = y2.copy()
        y3[:len(y1)] += y1

    func1(interval, y1, s1)
    func1(interval, y2, s2)
    func1(interval, y3, s2)

    w.write("sum2.wav", y3, s2, sampwidth=3)  # testing the sum

    """The dft of the speech is, of of course, much more complex and has many more frequencies in it while the
Exemplo n.º 7
0
def demon_noise(signal, chunk, freq):
    noise = list(chunks(signal, chunk))
    noise = random.sample(noise, len(noise))
    noise = np.concatenate(noise, axis=0)
    path = 'noise.wav'
    w.write("noise.wav", noise, freq, sampwidth=3)
    return path
Exemplo n.º 8
0
Arquivo: sd2.py Projeto: rec/sd2
def read(infile, outfile):
    samples = np.fromfile(infile, dtype='>i2')
    if len(samples) % 2:
        samples = samples[:-1]

    samples = samples.reshape(len(samples) // 2, 2)
    wavio.write(outfile, samples, FRAMERATE, sampwidth=2, scale='none')
Exemplo n.º 9
0
 def write_to_file(self, file):
     """Save file in a .wav format"""
     wavio.write(file,
                 self.data,
                 self.fs,
                 scale='none',
                 sampwidth=self.bytes)
Exemplo n.º 10
0
def doTheThing():
	start = datetime.now()
	print('doing the thing!')
	fs=44100
	duration = 5
	myrecording = sd.rec(fs * duration, samplerate=fs, channels=2)
	print("Recording Audio")
	sd.wait()
	wavio.write('temp.wav',myrecording,fs,sampwidth=2)
	temp = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp.wav")
	print(temp)
	r = sr.Recognizer()
	with sr.AudioFile(temp) as source:
	    audio = r.record(source)
	try:
	    query = r.recognize_google(audio)
	    print(search(query))
	    print("Google Speech Recognition thinks you said " + query)
	except sr.UnknownValueError:
	    print("Google Speech Recognition could not understand audio")
	except sr.RequestError as e:
	    print("Could not request results from Google Speech Recognition service; {0}".format(e))
	end = datetime.now()
	elapsed = end - start
	print('took about {} units of time'.format(elapsed.total_seconds()))
Exemplo n.º 11
0
def Main():
    verbose = True
    audio_in_path = './test_samples/153036.m4a'
    (data, sampleRate) = ExtractCompressedAudioNTS(audio_in_path)

    rescale = 1/(rms(data)+1e-8)/16
    data *= rescale

    if verbose:
        wavio.write('temp/loadcheck.wav', data,
                    sampleRate, (-1, 1), sampwidth=2)

    noiseReduceData = NoiseReduction(data, sampleRate, verbose)

    squawks = FindSquawks(noiseReduceData, sampleRate)

    os.system('mkdir -p squawk')
    index = 0
    for s in sorted(squawks, key=lambda squawk: squawk['duration']):
        sub = ExtractSquawkData(noiseReduceData, sampleRate, s)
        print(json.dumps(s))
        fileName = 'squawk/squawk%04d.wav' % index
        wavio.write(fileName, sub, sampleRate, (-1, 1), sampwidth=2)
        fileName = 'squawk/squawk%04d.json' % index
        with open(fileName, 'w') as f:
            f.write(json.dumps(s, sort_keys=True, indent=4))
        index = index+1
Exemplo n.º 12
0
def ExtractSquawks(dirName, fileName, meta):
    
    global GSquawkIndex
    GSquawkIndex=0
    verbose = True

    (data, sampleRate) = ExtractCompressedAudioNTS(dirName+'/'+fileName)

    rescale = 1/(rms(data)+1e-8)/16
    data *= rescale

    if verbose:
        wavio.write('temp/loadcheck.wav', data,
                    sampleRate, (-1, 1), sampwidth=2)

    noiseReduceData = NoiseReduction(data, sampleRate, verbose)

    squawks = FindSquawks(noiseReduceData, sampleRate)

    print('Squawk count : %d\n' % len(squawks))

    os.system('mkdir -p squawk')
    for s in sorted(squawks, key=lambda squawk: squawk['duration']):
        s['origin'] = fileName
        index = GSquawkIndex
        GSquawkIndex = GSquawkIndex+1
        sub = ExtractSquawkData(noiseReduceData, sampleRate, s)
        print(json.dumps(s))
        wavName = 'squawk/squawk%04d.wav' % index
        wavio.write(wavName, sub, sampleRate, (-1, 1), sampwidth=2)
        jsonName = 'squawk/squawk%04d.json' % index
        s.update(meta)
        with open(jsonName, 'w') as f:
            f.write(json.dumps(s, sort_keys=True, indent=4))
Exemplo n.º 13
0
    def wave(self,
             filename: str,
             key: int = CHROMATIC_SCALE,
             note_duration: int = DEFAULT_NOTE_DURATION,
             sample_rate: int = DEFAULT_SAMPLE_RATE) -> None:
        """Returns the hash as a wave file.

        # Args
        - *filename*: file path for the output wave file.
        - *key*: integer (see constants) corresponding to the musical key.
        - *note_duration*: duration of each note in seconds.
        - *sample_rate*: sample rate for the output audio.

        # Raises
        A ValueError if the key argument has one or fewer notes or more than
        twelve notes or if the sample_rate or note_duration are less than or
        equal to zero.
        """
        if filename == '':
            raise FileNotFoundError('Empty filename not permitted')
        wavio.write(
            file=filename,
            data=self.samples(key, note_duration, sample_rate),
            rate=sample_rate,
            sampwidth=2)
Exemplo n.º 14
0
def gen_C0_IRs(out_dir,IRs=100,buffersize=int(12E3),rev_prob=0.1,types=['EXP','HARM','RAND'],
               H=[16,32,64,81],passes=[1,2,3],harmonics=[1,2,4]):
    if not os.path.exists(out_dir): os.makedirs(out_dir)
    data = []
    for i in range(IRs):
        h = np.random.choice(passes)
        new = [0 for j in range(buffersize)]
        for y in range(h):
            s = np.random.choice(types)
            if s=='EXP':
                print('EXP')
                new = list(dsp.fade_out(dsp.impulse_exp(new),buffersize))
            if s=='HARM':
                print('HARM')
                r = np.random.choice(harmonics)
                for x in range(r):
                    new = list(dsp.fade_out(dsp.fft_high_pass(dsp.impulse_harm(new,H)),buffersize))
            if s=='RAND':
                print('RAND')
                new = list(dsp.fade_out(dsp.impulse_rand(new),buffersize))
            if np.random.choice([True,False],p=[2*rev_prob,1.0-2*rev_prob]):
                new = new[::-1]
        data += [dsp.fft_high_pass(new)]
    j = 0
    for i in range(len(data)):
        if j%10==0: #make a new directory if needed
            j,last_dir = 0,out_dir+'/'+str(i/10)+'/'
        if not os.path.exists(last_dir):
            os.makedirs(last_dir)
        wavio.write(last_dir+'W'+str(j)+'.wav',data[i],len(data[i]),sampwidth=2)
        j += 1
    return True
Exemplo n.º 15
0
    def test4(self):
        path = tempfile.mkdtemp()
        filename = os.path.join(path, "test4data.wav")
        data = np.zeros(32, dtype=np.int16)
        data[1::4] = 10000
        data[3::4] = -10000

        wavio.write(filename, data, 44100, sampwidth=1)
        try:
            f = wave.open(filename, 'r')
            self.assertEqual(f.getnchannels(), 1)
            self.assertEqual(f.getsampwidth(), 1)
            self.assertEqual(f.getframerate(), 44100)
            f.close()

            w = wavio.read(filename)
            self.assertEqual(w.rate, 44100)
            self.assertEqual(w.sampwidth, 1)
            self.assertEqual(w.data.dtype, np.uint8)
            self.assertEqual(w.data.shape, (32, 1))
            expected = 128*np.ones_like(data, dtype=np.uint8).reshape(-1, 1)
            expected[1::4, 0] = 255
            expected[3::4, 0] = 0
            np.testing.assert_equal(w.data, expected)
        finally:
            os.remove(filename)
            os.removedirs(path)
Exemplo n.º 16
0
    def save(self, filename):
        """Save sound in computer.

        :param: A name of the file to be saved.
        :type: str
        """
        wavio.write(filename, self.audio, self.sampling_ratio, sampwidth=2)
Exemplo n.º 17
0
    def test4(self):
        path = tempfile.mkdtemp()
        filename = os.path.join(path, "test4data.wav")
        data = np.zeros(32, dtype=np.int16)
        data[1::4] = 10000
        data[3::4] = -10000

        wavio.write(filename, data, 44100, sampwidth=1)
        try:
            f = wave.open(filename, 'r')
            self.assertEqual(f.getnchannels(), 1)
            self.assertEqual(f.getsampwidth(), 1)
            self.assertEqual(f.getframerate(), 44100)
            f.close()

            w = wavio.read(filename)
            self.assertEqual(w.rate, 44100)
            self.assertEqual(w.sampwidth, 1)
            self.assertEqual(w.data.dtype, np.uint8)
            self.assertEqual(w.data.shape, (32, 1))
            expected = 128*np.ones_like(data, dtype=np.uint8).reshape(-1, 1)
            expected[1::4, 0] = 255
            expected[3::4, 0] = 0
            np.testing.assert_equal(w.data, expected)
        finally:
            os.remove(filename)
            os.removedirs(path)
Exemplo n.º 18
0
def create_16_bit_wav(songpath,outpath):
    import wavio
    from scipy.io import wavfile

    rate, audio = wavfile.read(songpath)

    wavio.write(outpath, audio.astype(np.int16), rate, sampwidth=2)
Exemplo n.º 19
0
def get_shimmer_jitter_from_opensmile(audio, index, sr):
    wavio.write(f'temp_{str(index)}.wav', audio, sr, sampwidth=3)
    subprocess.call(
            ["SMILExtract", "-C", os.environ['OPENSMILE_CONFIG_DIR'] + "/IS10_paraling.conf", "-I",
             f"temp_{str(index)}.wav", "-O",
             f"temp_{str(index)}.arff"])
    # Read file and extract shimmer and jitter features from the generated arff file
    file = open(f"temp_{str(index)}.arff", "r")
    data = file.readlines()

    # First 3 values are title, empty line and name | Last 5 values are numeric data,
    # and bunch of empty lines and unwanted text
    # headers = data[3:-5]

    headers = data[3:data.index('@data\n')]
    headers = headers[:headers.index('@attribute class numeric\n')]

    # Last line of data is where the actual numeric data is. It is in comma separated string format. After splitting,
    # remove the first value which is name and the last value which is class
    numeric_data = data[-1].split(',')[1:-1]

    assert len(headers) == len(numeric_data), "Features generated from opensmile are not matching with its headers"

    # data_needed = {x.strip(): float(numeric_data[e]) for e, x in enumerate(headers) if 'jitter' in x or 'shimmer' in x}
    data_needed = [float(numeric_data[e]) for e, x in enumerate(headers) if 'jitter' in x or 'shimmer' in x]

    # clean up all files
    delete_file(f'temp_{str(index)}.wav')
    delete_file(f'temp_{str(index)}.arff')

    return data_needed
Exemplo n.º 20
0
def save_audio(filename, audio, sample_rate=16000, sample_depth=2):
    import wavio
    save_audio = (audio * np.iinfo(np.int16).max).astype(np.int16)
    wavio.write(filename,
                save_audio,
                sample_rate,
                sampwidth=sample_depth,
                scale='none')
Exemplo n.º 21
0
def wavwrite(data, fs, bit, fname):
    if USE_SCIPY:
        outdata = ( data * 2**(bit-1) ).astype(sp.int16)
        scipy.io.wavfile.write(fname, fs, outdata.T)
    elif USE_WAVIO:
        data_wavio = data * 2**(bit-1)
        sampwidth = bit/8
        wavio.write(fname, data_wavio, fs, sampwidth)
Exemplo n.º 22
0
def record():
    print("Startingggg!!!!")
    record=sd.rec(int(duration*freq), samplerate=freq,channels=2)

    sd.wait()
    write('recorddata0.wav',freq,record)
    wv.write('recording1.wav',record,freq,sampwidth=2)
    print("Finished!!!")
 def myRecording(self):
     myrecording = sd.rec(int(self.time_duration * self.fs),
                          samplerate=self.fs,
                          channels=2)
     print("Recording has started will last for ", self.time_duration)
     sd.wait()  # Wait until recording is finished
     wv.write(self.storage_address, myrecording, self.fs,
              sampwidth=2)  # Save as WAV file
Exemplo n.º 24
0
def save_audio(filename: str, audio: np.ndarray):
    import wavio
    save_audio = (audio * np.iinfo(np.int16).max).astype(np.int16)
    wavio.write(filename,
                save_audio,
                pr.sample_rate,
                sampwidth=pr.sample_depth,
                scale='none')
Exemplo n.º 25
0
def make_soundfile(hits, ITER, file_name):
    f = 240.0 # sound frequency (Hz)

    # Compute waveform samples
    x, rate = make_muted_sine(hits, f, ITER)

    # Write the samples to a file
    wavio.write(f"{file_name}.wav", x, rate, sampwidth=3)
Exemplo n.º 26
0
    def get_remap(self, tobrml, tobrmr):
        new_data = get_mat_value(tobrml, tobrmr)
        wavio.write("remap.wav",
                    new_data,
                    rate=self.wave.rate,
                    sampwidth=self.wave.sampwidth)

        return
Exemplo n.º 27
0
    def test1(self):
        with temporary_filepath("test1data.wav") as filename:
            wavio.write(filename, data1, 44100, sampwidth=3)

            self.check_basic(filename, nchannels=1, sampwidth=3,
                             framerate=44100)
            self.check_wavio_read(filename, rate=44100, sampwidth=3,
                                  dtype=np.int32, shape=(len(data1), 1),
                                  data=data1[:, None])
Exemplo n.º 28
0
 def export_morse_audio(self,
                        _word_,
                        file_name='morse_audio.wav',
                        frequency=450,
                        wpm=20):
     import wavio
     self._call_play_by_export = True
     wave = self.play_morse_code(_word_, frequency, wpm)
     wavio.write(file_name, wave, self._fs_, sampwidth=2)
Exemplo n.º 29
0
def save_audio(path, array, sampling=44100, sampling_width=4):
    """
        Parameters:
        path (str): Path where to save the audio file.
        array (np.array of floats): Array to be saved.
        sampling (int): Sampling rate of the stream.
        sampling_width (int): Sampling width of the stream.
    """
    wavio.write(path, array, rate=sampling, sampwidth=sampling_width)
    def __generateFile(self, path, sound):
        # plt.title(os.path.basename(path))
        # plt.plot(np.linspace(0, 1, len(sound)), sound)
        # plt.grid(True)
        # plt.xlabel('Seconds')
        # plt.ylabel('Amplitude [dB]')
        # plt.show()

        wavio.write(path, sound, self.rate, sampwidth=1, scale=(self.min_scale, self.max_scale))
Exemplo n.º 31
0
def generate_wav(audio, file_name, sample_rate=41000):
    """
    Generate .wav file from recorded audio
    :param audio: Numpy array of audio samples
    :param file_name: File name
    :param sample_rate: Audio sample rate. (Default = 41000)
    :return: None
    """
    wavio.write(file_name, audio, sample_rate, sampwidth=3)
Exemplo n.º 32
0
def save_selected_sound(audiodata, sampleRate, t1, t2, filename):
    # t1, t2 in seconds
    t1 = math.floor(t1 * sampleRate)
    t2 = math.floor(t2 * sampleRate)
    wavio.write(str(filename) + '.wav',
                audiodata[int(t1):int(t2)].astype('int16'),
                sampleRate,
                scale='dtype-limits',
                sampwidth=2)
Exemplo n.º 33
0
def write_mungo(out_dir,
                data,
                module='G0',
                prefix={'G0':'W','S0':'S','C0':'W','W0':'W'}):
    if not os.path.exists(out_dir): os.makedirs(out_dir)
    j = 0
    for i in range(len(data)):
        if j%10==0: #make a new directory if needed
            j,last_dir = 0,out_dir+'/'+str(i/10)+'/'
        if not os.path.exists(last_dir):
            os.makedirs(last_dir)
        wavio.write(last_dir+prefix[module]+str(j)+'.wav',data[i],len(data[i]),sampwidth=2)
        j += 1
    return True
Exemplo n.º 34
0
def gen_W0_WTs(out_dir,WTs=10,buffersize=int(4E3),C=[0,0,0,1,1,1],h_range=range(10),plot=False):
    if not os.path.exists(out_dir): os.makedirs(out_dir)
    data = []
    for i in range(WTs):
        h = h_range[i%(len(h_range))]
        data += [dsp.nonlin_shape(buffersize,C,h,plot)]
    j = 0
    for i in range(len(data)):
        if j%10==0: #make a new directory if needed
            j,last_dir = 0,out_dir+'/'+str(i/10)+'/'
        if not os.path.exists(last_dir):
            os.makedirs(last_dir)
        wavio.write(last_dir+'W'+str(j)+'.wav',data[i],len(data[i]),sampwidth=2)
        j += 1
    return True    
Exemplo n.º 35
0
    def test1(self):
        path = tempfile.mkdtemp()
        filename = os.path.join(path, "test1data.wav")
        wavio.write(filename, data1, 44100, sampwidth=3)
        try:
            f = wave.open(filename, 'r')
            self.assertEqual(f.getnchannels(), 1)
            self.assertEqual(f.getsampwidth(), 3)
            self.assertEqual(f.getframerate(), 44100)
            f.close()

            w = wavio.read(filename)
            self.assertEqual(w.rate, 44100)
            self.assertEqual(w.sampwidth, 3)
            self.assertEqual(w.data.dtype, np.int32)
            self.assertEqual(w.data.shape, (len(data1), 1))
            np.testing.assert_equal(w.data[:, 0], data1)
        finally:
            os.remove(filename)
            os.removedirs(path)
Exemplo n.º 36
0
def resample(dirName):
    """
    Resample to avoid high frq noise
    """
    for root, dirs, files in os.walk(str(dirName)):
        for file in files:
            if file.endswith('.wav'):
                # go through each segment
                file = root + '/' + file
                wavobj = wavio.read(file)
                audioData = wavobj.data
                if audioData.dtype is not 'float':
                    audioData = audioData.astype('float')  # / 32768.0
                if np.shape(np.shape(audioData))[0] > 1:
                    audioData = np.squeeze(audioData[:, 0])
                sampleRate = wavobj.rate
                import librosa
                if sampleRate != 16000:
                    audioData = librosa.core.audio.resample(audioData, sampleRate, 16000)
                    sampleRate = 16000
                    wavio.write(file[:-4] + '_down.wav', audioData.astype('int16'), sampleRate, scale='dtype-limits', sampwidth=2)
Exemplo n.º 37
0
    def test_clip(self):
        path = tempfile.mkdtemp()
        filename = os.path.join(path, "testdata.wav")
        data = np.array([-100, 0, 100, 200, 300, 325])

        wavio.write(filename, data, 44100, sampwidth=1, scale='none')
        try:
            f = wave.open(filename, 'r')
            self.assertEqual(f.getnchannels(), 1)
            self.assertEqual(f.getsampwidth(), 1)
            self.assertEqual(f.getframerate(), 44100)
            f.close()

            w = wavio.read(filename)
            self.assertEqual(w.rate, 44100)
            self.assertEqual(w.sampwidth, 1)
            self.assertEqual(w.data.dtype, np.uint8)
            self.assertEqual(w.data.shape, (len(data), 1))
            expected = np.array([0, 0, 100, 200, 255, 255],
                                dtype=np.uint8).reshape(-1, 1)
            np.testing.assert_equal(w.data, expected)
        finally:
            os.remove(filename)
            os.removedirs(path)
Exemplo n.º 38
0
    def test5(self):
        path = tempfile.mkdtemp()
        filename = os.path.join(path, "test5data.wav")
        data = np.zeros(32, dtype=np.int16)
        data[1::4] = 10000
        data[3::4] = -10000

        wavio.write(filename, data, 44100, sampwidth=2, scale='none')
        try:
            f = wave.open(filename, 'r')
            self.assertEqual(f.getnchannels(), 1)
            self.assertEqual(f.getsampwidth(), 2)
            self.assertEqual(f.getframerate(), 44100)
            f.close()

            w = wavio.read(filename)
            self.assertEqual(w.rate, 44100)
            self.assertEqual(w.sampwidth, 2)
            self.assertEqual(w.data.dtype, np.int16)
            self.assertEqual(w.data.shape, (32, 1))
            np.testing.assert_equal(w.data, data.reshape(-1, 1))
        finally:
            os.remove(filename)
            os.removedirs(path)
Exemplo n.º 39
0
def extractSegments(wavFile, destination, copyName, species):
    """
    This extracts the sound segments given the annotation and the corresponding wav file. (Isabel's experiment data extraction)
    """
    datFile=wavFile+'.data'
    try:
        wavobj = wavio.read(wavFile)
        sampleRate = wavobj.rate
        data = wavobj.data
        if os.path.isfile(datFile):
            with open(datFile) as f:
                segments = json.load(f)
            cnt = 1
            for seg in segments:
                if seg[0] == -1:
                    continue
                if copyName:    # extract all - extracted sounds are saved with the same name as the corresponding segment in the annotation (e.g. Rawhiti exp.)
                    filename = destination + '\\' + seg[4] + '.wav'
                    s = int(seg[0] * sampleRate)
                    e = int(seg[1] * sampleRate)
                    temp = data[s:e]
                    wavio.write(filename, temp.astype('int16'), sampleRate, scale='dtype-limits', sampwidth=2)
                elif not species:   # extract all - extracted sounds are saved with the original file name followed by an index starting 1
                    ind = wavFile.rindex('/')
                    filename = destination + '\\' + str(wavFile[ind + 1:-4]) + '-' + str(cnt) + '.wav'
                    cnt += 1
                    s = int(seg[0] * sampleRate)
                    e = int(seg[1] * sampleRate)
                    temp = data[s:e]
                    wavio.write(filename, temp.astype('int16'), sampleRate, scale='dtype-limits', sampwidth=2)
                elif species == seg[4]:   # extract only specific calls - extracted sounds are saved with with the original file name followed by an index starting 1
                    ind = wavFile.rindex('/')
                    ind2 = wavFile.rindex('\\')
                    filename = destination + '\\' + str(wavFile[ind2+1:ind]) + '-' + str(wavFile[ind + 1:-4]) + '-' + str(seg[4]) + '-' + str(cnt) + '.wav'
                    cnt += 1
                    s = int((seg[0]-1) * sampleRate)
                    e = int((seg[1]+1) * sampleRate)
                    temp = data[s:e]
                    wavio.write(filename, temp.astype('int16'), sampleRate, scale='dtype-limits', sampwidth=2)
    except:
        print ("unsupported file: ", wavFile)
Exemplo n.º 40
0
def main():

    files = [
        # "/home/nhilton/development/nsound/src/examples/california.wav",
        # "/home/nhilton/development/nsound/src/examples/mynameis.wav",
        # "/home/nhilton/development/nsound/src/examples/Temperature_in.wav",
        # "/home/nhilton/development/nsound/src/examples/walle.wav",
        # "/home/nhilton/development/nsound/src/examples/example1",
        # "empty.bin",
        "chirp1.wav",
    ]

    for i, f in enumerate(files):

        print('-------------------------------------------------------')
        print('Reading file')
        print('    in: %s'  % f)

        try:
            chunks = wavio.read_chunks(f)
        except wavio.InvalidRiffWave:
            print("    Not a RIFF WAVE!")
            continue

        s = json.dumps(chunks, indent = 4, separators = (', ', ' : '), sort_keys = True)

        for line in s.split('\n'):
            print('    %s' % line)

        x, sr = wavio.read(f)

        if x.ndim > 1:
            x = x[:,0]

        plt.figure()
        plt.plot(x, 'b-')
        plt.grid(True)
        plt.xlabel('sample bin')
        plt.ylabel('amplitude')
        plt.title('wav = %s' % f)

        # write out forward & reverse

        fout = 'fwd-%02d.wav' % i

        wavio.write(fout, x, sr, dtype = np.float32)

        print('Wrote %s' % fout)

        f = fout

        chunks = wavio.read_chunks(f)

        s = json.dumps(chunks, indent = 4, separators = (', ', ' : '), sort_keys = True)

        for line in s.split('\n'):
            print('    %s' % line)

        x, sr = wavio.read(f)

        if x.ndim > 1:
            x = x[:,0]

        plt.figure()
        plt.plot(x, 'b-')
        plt.grid(True)
        plt.xlabel('sample bin')
        plt.ylabel('amplitude')
        plt.title('wav = %s' % f)


    plt.show()
Exemplo n.º 41
0
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 23 15:47:31 2016

@author: SRINIVAS
"""

import numpy as np
import wavio
import sounddevice as sd
fs= 44100
a=0
duration=5
print(0)
recording = sd.rec(duration * fs, samplerate=fs, channels=2)
sd.wait()
print(0)

wavio.write('ine.wav',recording,rate=44100,sampwidth=3)
Exemplo n.º 42
0
def save_selected_sound(audiodata,sampleRate,t1,t2,filename):
        # t1, t2 in seconds
        t1 = math.floor(t1 * sampleRate)
        t2 = math.floor(t2 * sampleRate)
        wavio.write(str(filename) + '.wav', audiodata[int(t1):int(t2)].astype('int16'), sampleRate, scale='dtype-limits', sampwidth=2)