コード例 #1
0
ファイル: shuffle.py プロジェクト: ukzncompphys/lecture8_2016
def play_song(fname):
    faad='faad'
    to_exec=faad + ' -i '+ fname  #first, read header so we can report song info
    aa=subprocess.check_output(to_exec,stderr=subprocess.STDOUT,shell=True)
    nn=get_key(aa,'\ntitle:')  #we'll get name of song
    writer=get_key(aa,'\nwriter:')  #and composer

    myinfo=get_key(aa,'LC AAC') #we'll get some info about the file
    tags=myinfo.split()  #this splits strings into their pieces
    rate=tags[-2]
    nchan=tags[-4]
    length=tags[0]
    print 'playing ' + nn + ' by ' + writer + ' for ' + length + ' ' + tags[1]
    
    to_exec=faad+ ' -f2 -w -b4 ' + fname  #this magic command will have faad read data into float arrays
    ff=open('/dev/null','w')
    dd=subprocess.check_output(to_exec,stderr=ff,shell=True) #this calls faad to do the heavy lifting 
    ff.close()

    dat=numpy.fromstring(dd,dtype='float32') #convert string output from faad into numpy array
    nchan=numpy.int(nchan)
    dat=numpy.reshape(dat,[len(dat)/nchan,nchan])
    fs=numpy.int(rate) #get the sample rate the speakers are expecting
    sd.play(dat,fs,blocking=False) #play through speakers using sounddevice
    return numpy.float(length) #return length of song.  
コード例 #2
0
    def play(self, file_path):

        if self.convert:
            self.convert_mp3_to_wav(file_path_mp3=file_path)
        data, fs = sf.read(file_path)
        sd.play(data, fs)
        sd.wait()
コード例 #3
0
ファイル: encoder.py プロジェクト: chends888/CamFisComp
def generateSound(num, time, fs):
    n = time*fs
    x = np.linspace(0, time, n)
    if num == '0':
        freq1 = 1336
        freq2 = 941
    elif num == '1':
        freq1 = 1209
        freq2 = 697
    elif num == '2':
        freq1 = 1336
        freq2 = 697
    elif num == '3':
        freq1 = 1477
        freq2 = 697
    elif num == '4':
        freq1 = 1209
        freq2 = 770
    elif num == '5':
        freq1 = 1336
        freq2 = 770
    elif num == '6':
        freq1 = 1477
        freq2 = 770
    elif num == '7':
        freq1 = 1209
        freq2 = 852
    elif num == '8':
        freq1 = 1336
        freq2 = 852
    elif num == '9':
        freq1 = 1477
        freq2 = 852
    else:
        freq1 = 0
        freq2 = 0

    s1 = (np.sin(freq1*x*2*np.pi))
    s2 = (np.sin(freq2*x*2*np.pi))
    s = s1 + s2

    sd.play(s, 44100)
    sd.wait()

    # Plotting graphs
    plt.figure(1)
    plt.subplot(211)
    plt.plot(s1)
    plt.xlim(0, 250)
    
    plt.subplot(211)
    plt.plot(s2)
    plt.xlim(0, 250)

    plt.subplot(212)
    plt.plot(s)
    plt.xlim(0, 250)
    
    plt.show()
    return
コード例 #4
0
ファイル: sound.py プロジェクト: Tkizzy/sound-machine
def play_song(song, sample=SineWave):
    """
    Play a song.

    A song is a list of tuples of (frequency, duration, active time ratio).
    """

    def frames(f):
        return int(f * SAMPLE_RATE)

    compiled = []
    duration = 0

    for freq, dur, active in song:
        thissample = sample if freq else Sample
        compiled.append((sample(freq), frames(dur), frames(dur*active)))
        duration += frames(dur)

    out = numpy.empty((duration, 1))
    count = 0
    for sample, dur, active in compiled:
        for i in xrange(dur):
            if i < active:
                out[count + i] = sample.amplitude(i) * 0.8
            else:
                out[count + i] = 0
        count += dur

    print 'playing!'
    sd.play(out, blocking=True)
コード例 #5
0
def ellis_bpm(fname, start_bpm, hpss=True, hop_length=512, tightness=100.0, plot=False, sound=False):
    y, sr = librosa.load(fname, sr=None)
    log.debug(u'Estimating tempo: {}'.format(TERM.cyan(fname)))
    if hpss:
        log.debug(TERM.magenta("Getting percussive elements"))
        y_harmonic, y_percussive = librosa.effects.hpss(y)
        chunks = np.array_split(y_percussive, PLOT_SPLIT)
        log.debug(TERM.magenta("Estimating beats per minute"))
        bpm, beat_frames = librosa.beat.beat_track(y=y_percussive, sr=sr, start_bpm=start_bpm, hop_length=hop_length, tightness=tightness)
    else:
        log.debug(TERM.magenta("Estimating beats per minute"))
        bpm, beat_frames = librosa.beat.beat_track(y=y, sr=sr, start_bpm=start_bpm, hop_length=hop_length, tightness=tightness)
        chunks = np.array_split(y, PLOT_SPLIT)

    log.debug(u'Tempo: {:6.2f} bpm'.format(bpm))
    if plot:
        plt.figure(figsize=(16,10))

        curr_frame = 0
        for i in range(PLOT_SPLIT):
            plt.subplot(PLOT_SPLIT * 100 + 11 + i)
            plt.plot(curr_frame + np.arange(len(chunks[i])), chunks[i], 'g')
            for b in beat_frames:
                plt.axvline(x=b*hop_length, color='k')
            plt.xlim([curr_frame, len(chunks[i]) + curr_frame])
            curr_frame += len(chunks[i])
        plt.show(block=False)
    if sound:
        beat_times = librosa.frames_to_time(beat_frames, sr=sr, hop_length=hop_length)
        clicks = mir_eval.sonify.clicks(beat_times, sr, length=len(y))
        sd.play(y + clicks, sr)
        input('Press Return key to stop sound')
        sd.stop()
    return bpm
コード例 #6
0
	def play(self):
		# play from current position
		if not debug:
			while self.pv.getSample(self.currentPosition) is not None:
			
				# use nsound to play the sample
				# make sure player is waiting correct amount of time before plating next sample
				pass

		else:
			sampleNumber = self.debugGetSample(self.currentPosition)
			while sampleNumber is not None:
				print sampleNumber
				
				self.currentPosition += 1.0 / float(self.SAMPLES_PER_SECOND)
				sampleNumber = self.debugGetSample(self.currentPosition)
			print len(self.debugSamples)
			#sd.play(self.debugSamples, self.SAMPLES_PER_SECOND)

			#plt.plot(self.debugSamples)
			#plt.show()

			#f, df = 440.0, 44100.0
			#t = r_[0.0:1.0:1/df]
			#data = np.cos(2 * pi * f * t)
			#play(data)
			#data = np.random.uniform(-1, 1, 44100)

			data = self.debugSamples
			scaled = np.int16(data/np.max(np.abs(data)) * 32767)
			
			plt.plot(scaled)
			plt.show()
			
			sd.play(scaled, self.SAMPLES_PER_SECOND)
コード例 #7
0
ファイル: musicplayer.py プロジェクト: knnnrd/RoboLink-DSP
    def run(self):
        while not self.exitFlag:
            # qsize() is unreliable
            if not self.q.empty() and self.q.qsize() > self.minblocks:
                # Get all values from all chunks and put in a list
                data = []
                n = 0
                for n in range(self.minblocks):
                    # get minblocks amount of chunks
                    tmp = self.q.get()

                    n = n + 1

                    m = 0
                    for m in range(len(tmp)):
                        # append all values in chunk to data list
                        data.append(tmp[m])
                        m = m + 1

                    self.i = self.i + 1

                print("Musicplayer: Playing data with length: ", len(data))
                sd.play(data, self.Fs)

            time.sleep(self.sleeptime)
コード例 #8
0
ファイル: player.py プロジェクト: maehler/raspberry-radio
def play(url):
    f = urlopen(url)

    chunk = f.read(4096)
    bchunk = np.array(list(chunk), dtype=np.int16)

    sd.play(bchunk, 44100)
コード例 #9
0
    def play_audio(self):
        if self.play_button.isChecked():
            data = preprocess_audio(self.data, spikes_only=self.play_spike_audio)

            # Track progress
            if settings.show_audio_line:
                self.audio_line = self.addLine(x=0)
                self.audio_timer = pg.QtCore.QTimer()
                self.audio_timer.setInterval(AUDIO_TIMER_UPDATE)
                self.audio_timer.timeout.connect(self.update_audio_line)
            sd.stop()
            sd.play(data)
            if settings.show_audio_line:
                self.audio_timer.start()

            # Notify all other audio components
            self.guard = True
            self.src.s.stop_audio.emit()
            
        else:
            sd.stop()
            self.audio_timer.stop()
            if settings.show_audio_line:
                self.audio_line.hide()
                self.audio_line = None
コード例 #10
0
ファイル: sound.py プロジェクト: morse-talk/morse-talk
def preview_wave(message, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, word_ref=WORD):
    """
    Listen (preview) wave

    sounddevice is required http://python-sounddevice.readthedocs.org/
    $ pip install sounddevice
    """
    samp_nb = samples_nb(message=message, wpm=wpm, framerate=framerate, word_spaced=False)
    import sounddevice as sd
    lst_bin = _encode_binary(message)
    amplitude = _limit_value(amplitude)
    seconds_per_dot = _seconds_per_dot(word_ref)  # 1.2
    a = [calculate_wave(i, lst_bin, wpm, frequency, framerate, amplitude, seconds_per_dot)
         for i in range(samp_nb)]
    sd.play(a, framerate, blocking=True)
コード例 #11
0
ファイル: audioshift.py プロジェクト: sw8f17/app_testing
def offline():
    print("Offline analysis")
    duration = 5 # seconds
    fs = 48000
    sd.default.samplerate = fs
    audio = sd.rec(duration * fs, channels=2, dtype="float64")
    sd.wait()

    print("  [{} channels, {:.2f} sec. {} Hz]".format(audio.shape[1], audio.shape[0] / fs, fs))
    for pair in combinations(range(audio.shape[1]), 2):
        print("  Ch. {} -> {}:".format(*pair), end='')
        shift = _compute_shift(audio[:, pair[1]], audio[:, pair[0]])
        print(" {:>5} sample(s) [{:>7,.3f} ms]".format(shift, shift / (fs / 1000)))

    sd.play(audio)
    sd.wait()
コード例 #12
0
def get_hpss(filename):
    # Get sound file (input sr = None, as we don't want to resample)
    log.debug(u"Loading {}".format(TERM.green(filename)))
    y, sr = librosa.load(filename, sr=None)
    log.debug(TERM.magenta("Filtering high frequencies"))
    y_filt = fir_lowpass(y, 5000, sr)
    # Get the percussive and harmonic elements
    log.debug(TERM.magenta("Splitting into harmonic and percussive"))
    y_harmonic, y_percussive = librosa.effects.hpss(y_filt)
    y_spss = {"harmonic":y_harmonic, "percussive":y_percussive}
    # Play each in turn
    while True:
        component = get_response("Which component do you want to play?", ["harmonic", "percussive"], numbered=True)
        if component is None:
            return None
        sd.play(y_spss[component], sr)
        input('Press Return key to stop sound')
        sd.stop()
コード例 #13
0
def SoundCalOut(Rate, Freq, WaveDur):
    """ Generate a sine wave from 1 to -1 """
    Pulse = GenSineWave(Rate, Freq, 1, WaveDur)
    
    SD.default.device = 'system'
    SD.default.samplerate = Rate
    SD.default.channels = 1
    SD.default.blocksize = 0    
    SD.default.latency = 'low'
    
#    Stream = SD.OutputStream()
#    
#    print('Playing... ', end='')
#    with Stream: 
#        for PulseNo in range(SoundPulseNo):
#            Stream.write(Pulse)
#   
    print('Playing...', end='')
    SD.play(Pulse, blocking=True);
    print('Done.')
    
    return(None)
コード例 #14
0
ファイル: audio.py プロジェクト: pabloriera/pymam
def sound(x, fs=44100, blocking = True):

    """
    Play sound from x array at given sampling rate
    """
    
    if x.ndim==1:
        ch = 1
    elif x.ndim==2:
        if 1 in x.shape:
            x = x.flatten()
            ch = 1
        elif x.shape[0]==2:
            ch = 2
            x = x.T
        elif x.shape[1]==2:
            ch = 2
             
    elif x.ndim>2 or x.shape[1]>2:
        print('Error: 1-D array for mono, or 2-D array where rows should be the number of channels, 1 (mono) or 2 (stereo)')
        return
        
    if audio_ok:
        
        if x.ndim==2 and x.shape[0]==2:
            x=x.T
            
        play(x,fs)

        if blocking:

            pause(float(x.shape[0])/fs)


    else:
        warnings.warn('Cannot play sound, no sounddevice o audiolab module.')
コード例 #15
0
ファイル: test2.py プロジェクト: knnnrd/RoboLink-DSP
import pygame
import wave
import sounddevice as sd

pygame.mixer.init()

file = wave.open("Alarm01.wav")
#s = pygame.mixer.Sound("Alarm01.wav")
#file.play()
sd.play(file)
コード例 #16
0
random.seed()

wave_dict = []

# import Tkinter
# from Tkinter import *
# import tkMessageBox
#
# top = Tkinter.Tk()
# top.title("Fourier Synth")
# w = Canvas(top, width=500, height=500)
# w.grid(row=4, column=1,sticky=W)
# top.mainle
t=0
while True:
    wave_dict = []
    melody_speed = random.randint(12000,64000)
    for i in range(0,random.randint(1,10)):
        wave_dict.append({"freq":random.randint(1,2000),"melody_speed": ,"melody":[random.randint(50,200)/100.0],"amp":random.randint(0,100)/100.0,"phase":random.randint(1,314)/100.0,"LFO_freq": random.randint(1,1000)/100.0,"LFO_phase":random.randint(1,314)/100.0,"LFO_F":random.randint(1,100)/100.0,"LFO_A":random.randint(1,100)/100.0,"LFO_P":random.randint(1,314)/100.0})
    input_array = []
    for i in range(t,int(48000*20)+t):
        amplitude = 0.0
        for wave in wave_dict:
            LFO_amp = math.sin((i*wave["LFO_freq"])/7000.0+wave["LFO_phase"])
            amplitude += math.sin((i*(wave["freq"]+(LFO_amp*wave["LFO_F"])))/7000.0+(wave["phase"]+(LFO_amp*wave["LFO_P"])))*(wave["amp"]+(LFO_amp*wave["LFO_A"]))
        input_array.append(amplitude)
    array = np.array(input_array)
    sd.wait()
    sd.play(array,48000)
    t+=480000*1
コード例 #17
0
ファイル: audition.py プロジェクト: steveb/bogt
 def play(self):
     import sounddevice as sd
     sd.default.channels = 2
     sd.default.samplerate = self.sample_rate
     sd.play(self.play_data, self.sample_rate)
     sd.wait()
コード例 #18
0
ファイル: myaudiolib.py プロジェクト: finiteautomata/habla
def reproducir(onda):
    play(to_wav(onda))
    sd.wait()
コード例 #19
0
um = s697 + s1209
dois = s697 + s1336
tres = s697 + s1477
quatro = s770 + s1209
cinco = s770 + s1336
seis = s770 + s1477
sete = s852 + s1209
oito = s852 + s1336
nove = s852 + s1477
zero = s941 + s1336

while True:

    if keyboard.is_pressed('1'):
        sd.play(um)
        sd.wait()
        signal.plotFFT(um, fs)
        print("1")
        sd.stop()

    if keyboard.is_pressed('2'):
        sd.play(dois)
        sd.wait()
        signal.plotFFT(dois, fs)
        print("2")
        sd.stop()

    if keyboard.is_pressed('3'):
        sd.play(tres)
        sd.wait()
コード例 #20
0
ファイル: play_note.py プロジェクト: dilawar/MyPiano
def play_note_sounddevice(notePath, duration):
    data, fs = sf.read(notePath, dtype='float32')
    sd.play(data, fs)
    time.sleep(duration)
    return True
コード例 #21
0
ファイル: sweep.py プロジェクト: carebare47/opencv_laser_harp
def play_stereo_tone(left_frequency, right_frequency, duration):
    sd.play(gen_stereo(left_frequency, right_frequency, duration), fs)
    sd.wait()
コード例 #22
0
ファイル: play_dtmf.py プロジェクト: sourceperl/sandbox
 def play(self):
     sounddevice.play(np.array(self.wav, dtype=np.int16),
                      samplerate=self.f_ech,
                      blocking=True)
コード例 #23
0
 def sound_once(self):
     sounddevice.play(self.sound, self.sound_fs)
コード例 #24
0
x, fs = librosa.load('../data/f1_005.wav', dtype='double', sr=None)

_f0, t = pw.dio(x, fs)  # raw pitch extractor
f0 = pw.stonemask(x, _f0, t, fs)  # pitch refinement
sp = pw.cheaptrick(x, f0, t, fs)  # extract smoothed spectrogram
ap = pw.d4c(x, f0, t, fs)  # extract aperiodicity
#y = pw.synthesize(f0*2**(3/12), sp, ap, fs)
#mix = y[0:len(x)-len(y)] + x
#sd.play(mix, fs)

chorus = np.zeros(f0.size)
phonetic = [16.352, 18.354, 20.602, 21.827, 24.5, 27.5, 30.868]
for k, freq_f0 in enumerate(f0):
    if freq_f0 == 0:
        continue
    temp = freq_f0 / phonetic
    log2temp = [math.log2(i) for i in temp]
    diff = list(map(sub, log2temp, [round(i) for i in log2temp]))
    diff = [abs(i) for i in diff]
    idx = diff.index(min(diff))
    if idx == 0 or idx == 3 or idx == 4:
        chorus[k] = freq_f0 * 2**(4 / 12)
    else:
        chorus[k] = freq_f0 * 2**(3 / 12)

y = pw.synthesize(chorus, sp, ap, fs)
mix = y[0:len(x) - len(y)] * 0.6 + x
sd.play(mix, fs)

write('f1_005_chorus_up3.wav', fs, mix)
コード例 #25
0
 def playSound2(self, n):
     sd.play(self.inverse[n], self.rate)
コード例 #26
0
 def playSound(self):
     sd.play(self.ywav1[1], self.fs_rate)
figure(6)
stem(k,abs(fft(x))/M,'r')
grid(True);
ylim([-.01, 1.25]);
xlim([-21 ,21])
xlabel('FFT bins');
figure(7)
stem(k*fs/M,abs(fft(x))/M,'r')
grid(True);
ylim([-.01, 1.25]);
xlabel('Frequency (Hz)');
xlim([-55 ,55])


fs = 22050.0;
n = arange(4*fs);
t = n/fs;
x = cos(2000*pi*t*(t+2))
import sounddevice
#sounddevice.play(x,samplerate=22050)


fs = 8000.0;
n = arange(4*fs);
t = n/fs;
x = cos(2000*pi*t*(t+2))
sounddevice.play(x,samplerate=8000)
figure(8)
specgram(x, NFFT = 1000, Fs= 8000, noverlap=500)
xlabel('Time (seconds)')
ylabel('Frequency (Hz)')
コード例 #28
0
#def playFinished(client, userdata, msg):
#    print(msg.topic)

def stop():
    global _RUNNING
    _RUNNING = False

if __name__ == '__main__':
    print('Starting hermes audio player')

    # init GPIO if not done yet
    initGpio()

    # load empty wave file to prevent lag on playing first message
    data, fs = soundfile.read('void.wav', dtype='float32')
    sounddevice.play(data, fs, device=args.outputDevice)
    status = sounddevice.wait()
    if status:
        print('Error during playback: ' + str(status))

    lmsServer = LMSServer(lmsHost[0], lmsHost[1])
    lmsPlayer = LMSPlayer(args.macAddress, lmsServer)

    mqttClient = mqtt.Client()
    mqttClient.on_connect = onConnect
    mqttClient.message_callback_add("hermes/audioServer/{}/playBytes/#".format(args.siteId), playBytes)
#    mqttClient.message_callback_add("hermes/audioServer/{}/playFinished/#".format(args.siteId), playFinished)
    mqttClient.connect(mqttHost[0], int(mqttHost[1]))
    mqttClient.loop_start()

    try:
コード例 #29
0
ファイル: poise.py プロジェクト: razh/poise
def noise(duration):
    data = np.random.uniform(-1, 1, fs * duration)
    sd.play(data, blocking=True)
コード例 #30
0
def play_audio(signal, samplerate, seconds=5):
    sd.play(signal, samplerate)
    sd.sleep(int(seconds) * 1_000)
    sd.stop()
コード例 #31
0
ファイル: test.py プロジェクト: ankushjindal/system_practicum
import io
import math
from pprint import pprint
from urllib.request import urlopen
import soundfile as sf

url = "http://tinyurl.com/shepard-risset"
data, fs = sf.read(io.BytesIO(urlopen(url).read()))

import sounddevice as sd
sd.play(data, fs)

fs, duration = 44100, 1.5
data = sd.rec(duration * fs, samplerate=fs, channels=2)

sf.write('file.mp3', data, fs)

fs = 44100/20
data = []
msg = 'Hello World!'
time_to_play = 0.5
time_of_char = int(fs*time_to_play/len(msg))

for char in msg:
    asci = ord(char)
    data.extend([[math.cos(_*asci), math.cos(_*asci)] for _ in range(time_of_char)])

sd.play(data, fs, blocking=False)
コード例 #32
0
parser.add_argument('-l',
                    '--list-devices',
                    action='store_true',
                    help='show list of audio devices and exit')
args, remaining = parser.parse_known_args()
if args.list_devices:
    print(sd.query_devices())
    parser.exit(0)
parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[parser])
parser.add_argument('filename',
                    metavar='FILENAME',
                    help='audio file to be played back')
parser.add_argument('-d',
                    '--device',
                    type=int_or_str,
                    help='output device (numeric ID or substring)')
args = parser.parse_args(remaining)

try:
    data, fs = sf.read(args.filename, dtype='float32')
    sd.play(data, fs, device=args.device)
    status = sd.wait()
except KeyboardInterrupt:
    parser.exit('\nInterrupted by user')
except Exception as e:
    parser.exit(type(e).__name__ + ': ' + str(e))
if status:
    parser.exit('Error during playback: ' + str(status))
コード例 #33
0
ファイル: sotest.py プロジェクト: kavinfd/til
import sounddevice as sd
(fs1, x) = read('Traffic_stereo.wav', 'rb')
sd.play(x, fs1)
コード例 #34
0
ファイル: voicer.py プロジェクト: dabarkster/escapee-greetor
try:
    from matplotlib.animation import FuncAnimation
    import matplotlib.pyplot as plt
    import numpy as np
    import sounddevice as sd
    import soundfile as sf

    with sf.SoundFile(wav_file) as f:
        data = f.buffer_read(BLOCK * 50, ctype='float')
 
    #block = sf.blocks(wav_file, blocksize=2048, overlap=512)
    #soundfile = sf.SoundFile(wav_file)
    #data = soundfile.read(2048)
    print(data)
    #print(soundfile)
    sd.play(data)
    #print(block)
    while True:
        pass

    #outstream = sd.OutputStream(
    #    device=0, channels=max(f.channels),
    #    samplerate=f.samplerate, callback=audio_callback)

    print(len(data))



    #if args.list_devices:
    #    print(sd.query_devices())
    #    parser.exit(0)
コード例 #35
0
def sound(track):
    sd.play(track, 44000)
コード例 #36
0
ファイル: ui.py プロジェクト: zxy2020/zhrtvc
 def play(self, wav, sample_rate):
     sd.stop()
     sd.play(wav, sample_rate)
     sd.wait()
コード例 #37
0
 def play(self, event):
     sd.play(self.data.ifft, self.data.fs)
     time.sleep(len(self.data.input_sound) / self.data.fs)
     sd.stop()
コード例 #38
0
import sounddevice as sd
sd.default.latency = 'low'
sd.default.device = 4
sd.default.channels = 2
fs = 44100
sd.default.samplerate = fs

duration = 5
print(1)
myrecording = sd.rec(int(duration * fs))
print(2)
sd.wait()
print(3)
print(myrecording)
print(4)
sd.play(myrecording)
input()
print(5)
コード例 #39
0
ファイル: audio_processing_basic.py プロジェクト: pengge/SWDT
if 'posix' == os.name:
    #dataset_home_dir_path = '/home/sangwook/my_dataset'
    dataset_home_dir_path = '/home/HDD1/sangwook/my_dataset'
else:
    dataset_home_dir_path = 'D:/dataset'

data_dir_path = dataset_home_dir_path + '/failure_analysis/defect/knock_sound/500-1500Hz'

#--------------------------------------------------------------------

import numpy as np
import sounddevice as sd

fs = 44100
data = np.random.uniform(-1, 1, fs)
sd.play(data, fs)

sd.default.dtype

sd.query_devices()

sd.default.samplerate = 44100
# A single value sets both input and output at the same time.
#sd.default.device = 'digital output'
#sd.default.device = 7
# Different values for input and output.
sd.default.channels = 5, 7

sd.play(data)

sd.default.reset()
コード例 #40
0
def play(wave, duration, sample_rate):

    sd.play(wave, sample_rate)
    time.sleep(duration)
    sd.stop()
コード例 #41
0
ファイル: SoundBoard.py プロジェクト: francis-ng/pysoundboard
 def play(self, id):
     data, fs = self.audiofile_cache[id]
     sd.play(data, fs)
コード例 #42
0
    carry = (np.sin(15000*x*2*np.pi))
    data = data * carry

    # Plot fourier transform
    plotFFT(data, 'Fourier after modulation')

    return data


############################################################
####################      DECODING      ####################
############################################################


# Multiply by carry
data = readFile()
n = len(data)
x = np.linspace(0,20, n)
carry = (np.sin(15000*x*2*np.pi))
data = data * carry


# Appliyng low pass filter
data = lfilter(taps, 1.0, data)

# Plot fourier transform
plotFFT(data, 'Fourier after demodulation')

# Play demodulated wave
sd.play(data, 44100)
sd.wait()
コード例 #43
0
ファイル: sweep.py プロジェクト: carebare47/opencv_laser_harp
def play_two_waves(wave_A, wave_B):
    stereo_wave = np.column_stack((wave_A, wave_B))
    sd.play(stereo_wave, fs)
    sd.wait()
コード例 #44
0
ファイル: Intruder.py プロジェクト: orcapt/orca_python
            sd.wait()
            fay=[]
            yaf=[]
            fred=math.ceil(fs*duration)-10
            for p in range(1,fred):
                fay.append(recording[p][0])
            for elem in fay:
                yaf.append(abs(elem))
        a=a+1
        
        krow.append(np.mean(yaf))
        for elem in krow:
            hire.append(abs(np.mean(krow)-elem))
        
        if np.mean(krow)<np.mean(yaf)-np.mean(hire):
           fp = wave.open('int.wav')
           nchan = fp.getnchannels()
           N = fp.getnframes()
           dstr = fp.readframes(N*nchan)
           data = numpy.fromstring(dstr, numpy.int16)
           data = numpy.reshape(data, (-1,nchan))
           fs= 30010
           duration=2
           sd.play(data,fs)
           sd.wait()
           print('intruder!!!')
        else:
            print('Nothing')
    except:
        pass
コード例 #45
0
ファイル: poise.py プロジェクト: razh/poise
def sin(frequency, duration):
    samples = np.arange(fs * duration) / fs
    waveform = np.sin(2 * np.pi * frequency * samples)
    sd.play(waveform, blocking=True)
コード例 #46
0
            print("Created the mel spectrogram")

            ## Generating the waveform
            print("Synthesizing the waveform:")
            # Synthesizing the waveform is fairly straightforward. Remember that the longer the
            # spectrogram, the more time-efficient the vocoder.
            generated_wav = vocoder.infer_waveform(spec)

            ## Post-generation
            # There's a bug with sounddevice that makes the audio cut one second earlier, so we
            # pad it.
            generated_wav = np.pad(generated_wav, (0, synthesizer.sample_rate),
                                   mode="constant")

            # Play the audio (non-blocking)
            if not args.no_sound:
                sd.stop()
                sd.play(generated_wav, synthesizer.sample_rate)

            # Save it on the disk
            fpath = "demo_output_%02d.wav" % num_generated
            print(generated_wav.dtype)
            librosa.output.write_wav(fpath, generated_wav.astype(np.float32),
                                     synthesizer.sample_rate)
            num_generated += 1
            print("\nSaved output as %s\n\n" % fpath)

        except Exception as e:
            print("Caught exception: %s" % repr(e))
            print("Restarting\n")
コード例 #47
0
#!/usr/bin/env python3
"""Load an audio file and play its contents.

PySoundFile (https://github.com/bastibe/PySoundFile/) has to be installed!

"""
import argparse
import logging

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("filename", help="audio file to be played back")
parser.add_argument("-d", "--device", type=int, help="device ID")
args = parser.parse_args()

try:
    import sounddevice as sd
    import soundfile as sf
    data, fs = sf.read(args.filename, dtype='float32')
    sd.play(data, fs, device=args.device, blocking=True)
    status = sd.get_status()
    if status:
        logging.warning(str(status))
except BaseException as e:
    # This avoids printing the traceback, especially if Ctrl-C is used.
    raise SystemExit(str(e))
コード例 #48
0
ファイル: synth.py プロジェクト: Kronstrand/drone-synth

# combine all waveforms
def combineWaveforms(waveforms):
    waveform = waveforms[0]
    n_waveforms = len(waveforms)
    for i in range(1, n_waveforms):
        waveform += waveforms[i]
    waveform = waveform / n_waveforms
    return waveform


waveform = combineWaveforms(waveforms)
attinuated_waveform = waveform * volume

sd.play(attinuated_waveform, sps, loop=True)

key_sensitivity = 0.03

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                if volume + key_sensitivity > 1:
                    volume = 1
                else:
                    volume += key_sensitivity
            if event.key == pygame.K_DOWN:
                if volume - key_sensitivity < 0:
コード例 #49
0
ファイル: utils.py プロジェクト: evanjbowling/cs598ps
def play_sample(sample,samplerate=22050,blocking=True):
    sd.play(sample, samplerate=samplerate,blocking=blocking)
コード例 #50
0
def play(data: np.array, rate: int=FS) -> None:
    """ Plays a song to the default speaker. """
    sd.play(data, rate)
    sd.wait()
import sounddevice as sd
import numpy as np

fs=44100
duration = 5  # seconds
myrecording = sd.rec(duration * fs, samplerate=fs, channels=2,dtype='float64')
print("Recording Audio")
sd.wait()
print("Audio recording complete , Play Audio")
sd.play(myrecording, fs)
sd.wait()
print("Play Audio Complete")
コード例 #52
0
    "B": [1, 3],
    "7": [2, 0],
    "8": [2, 1],
    "9": [2, 2],
    "C": [2, 3],
    "*": [3, 0],
    "0": [3, 1],
    "#": [3, 2],
    "D": [3, 3]
   }

valid_digits = "0123456789*#ABCD"

duration = 0.5
volume = 0.5
fs = 44100  # sampling rate

while True:
    digits = list(input("Enter the digits: ").replace(" ", ""))
    if (all(d in valid_digits for d in digits)):
        for i in digits:
            f1 = low_freq[digits_tones[i][0]]
            f2 = high_freq[digits_tones[i][1]]
            s1 = np.sin(2 * np.pi * np.arange(fs * duration) * f1 / fs)
            s2 = np.sin(2 * np.pi * np.arange(fs * duration) * f2 / fs)

            sd.play(s1 * volume + s2 * volume)
            time.sleep(1)
    else:
        print("wrong input..")
コード例 #53
0
ファイル: slower.py プロジェクト: jenniferzhu/msan501
import soundfile as sf    # Use this package
import sounddevice as sd  # and this one

kiss, samplerate = sf.read('Kiss.aiff')  # load Kiss.aiff into kiss variable
sd.play(kiss, samplerate*.8)             # play the music at 80% speed
sd.wait()                                # wait until music finishes before exiting
def PlayBack(Signal, Fs):
    sd.play(Signal, Fs, blocking=True)
コード例 #55
0
def playback(y, sr):
    print("Playback samplerate:", sr)
    sd.play(y, sr)  # play audio
コード例 #56
0
def play_speech(rec):
    print('Playing')
    sd.play(rec)
コード例 #57
0
ファイル: puretone.py プロジェクト: jenniferzhu/msan501
import numpy
import sounddevice as sd

fs = 44100 # sampling frequency
T = 1.5    # seconds
t = numpy.linspace(0, T, int(T*fs), endpoint=False) # time variable
y = numpy.sin(2*numpy.pi*1000*t)                    # pure sine wave at 1000 Hz
sd.play(y, fs)
sd.wait()
コード例 #58
0
plt.tight_layout(0)
plt.show()

# plot transformations
n = 1
for xx in m, m2:
    for x in xx:
        plt.subplot(2, len(s), n)
        specshow(x, x_axis='linear')
        n += 1
plt.tight_layout(0)
plt.show()

# play reconstructions
for x, x2 in zip(w, w2):
    sd.play(x, sr, blocking=True)
    sd.play(x2, sr, blocking=True)

from util_np import r2c
from util_io import save, save_boxcar

plot = lambda x: specshow(np.log(1e-8 + np.abs(x)))

wav, sr = load(path('LJ001-0008'), sr=None)
frame = librosa.stft(wav, 512, 256)
plot(frame[:-1])
plt.savefig("../docs/presentation/image/original.pdf",
            bbox_inches='tight',
            pad_inches=0)

# wav = librosa.istft(frame, 256)
コード例 #59
0
ファイル: magpy.py プロジェクト: dustindikes/magpy
#!/usr/bin/env python

# MagPy - Magstripe reader

import sounddevice as sd

fs = 44100
duration = 5  # seconds

sd.default.samplerate = fs
sd.default.channels = 2
#sd.default.device = 0

print('RECORDING')
rec = sd.rec(duration*fs,device=1)

sd.wait()

#for r in rec:
#    print r

print('PLAYING')
sd.play(rec, fs, device=2)

sd.wait()
コード例 #60
0
numSamples = fs * recLength
times = np.linspace(0, recLength, numSamplesRec)

rec = sd.rec(numSamplesRec, samplerate=fs, channels=2)
rec = rec[:, 0]

sd.wait()

#%% plot and play audio
plt.figure(3)
plt.plot(times, rec)
plt.xlabel("time")
plt.ylabel("signal value")
plt.title("og recording")

sd.play(rec, fs)
sd.wait()

#%% shorten audio
startSampleShort = 0
timesShort = times[startSampleShort:startSampleShort + numSamplesAnalyze]
signal = rec[startSampleShort:startSampleShort + numSamplesAnalyze]
#signal = sampleAudio

sd.play(signal, fs)
sd.wait()

plt.figure(3)
plt.plot(timesShort, signal)
plt.xlabel("time")
plt.ylabel("signal value")