示例#1
0
class CSoundTestApp(App):

    __version__ = "0.1"
    csound = csnd6.Csound()
    perf = csnd6.CsoundPerformanceThread(csound)

    def build(self):
        screen = Widget()
        play_button = Button()
        play_button.text = 'Play ►'
        play_button.on_press = self.play
        screen.add_widget(play_button)
        return screen

    def destroy_settings(self):
        csnd6.csoundDestroy(self.csound)

    def play(self):
        if self.perf.isRunning():
            self.perf.Stop()
        else:
            # The '-odac' parameter specifies output to DAC. Otherwise it saves a WAV file.
            self.csound.Compile('-odac', 'Noise.csd')
            self.csound.Perform()
            self.perf.Play()
示例#2
0
def main(csound_file):
    c = CosmoHat()
    try:
        while True:
            cs = csnd6.Csound()
            res = cs.Compile(csound_file)
            if res == 0:
                perf = csnd6.CsoundPerformanceThread(cs)
                perf.Play()
                try:
                    run(c, cs, perf)
                finally:
                    perf.Stop()
                    perf.Join()
                    break
            # Script stopped or didn't compile. Blink leds a couple of times
            on = {}
            off = {}
            for i in range(c.nleds):
                on[i] = True
                off[i] = False
            for i in range(5):
                for j in range(2):
                    c.set_leds(on)
                    sleep(0.1)
                    c.set_leds(off)
                    sleep(0.05)
                sleep(0.5)
    finally:
        c.stop()
示例#3
0
    def __init__(self, csoundFile):
        """
        Class constructor.
        
        @param self: The object pointer.
        """

        self.isRunning = True
        """A flag that keeps the thread running, can be deleted when we start using csnd.PerformanceThread properly"""

        print 'commandline', csoundCommandline.csoundCommandline
        """The Csound commandline read from file "csoundCommandLine.py", setting options for audio i/o and buffers."""
        comlineParmsList = csoundCommandline.csoundCommandline.split(' ')

        # Create an instance of Csound, set orchestra, score and command line parameters
        self.csound = csnd.Csound()
        arguments = csnd.CsoundArgVList()
        arguments.Append("dummy")
        arguments.Append("%s.orc" % csoundFile)
        arguments.Append("%s.sco" % csoundFile)
        for item in comlineParmsList:
            arguments.Append("%s" % item)
        t = self.csound.Compile(arguments.argc(), arguments.argv())
        print 'test:', t
        self.hadronLoaded = False
        """Flag to test if Csound is finished loading"""

        self.performanceThread = csnd.CsoundPerformanceThread(self.csound)
        """The C++ csound performance thread"""
示例#4
0
 def __init__(self):
     self.currentMidiPort = -1  # not used in MaxPort
     self.latency = 1000  # used by pypm to specify MIDI latecny, does not seem to have any effect
     self.midiOut = None
     self.pyext = None  #if we are in a Max environment, this will be set to pyext.MaxPyExt()
     self.csound = csnd6.Csound()
     self.startTime = datetime.datetime.now()
     self.performance = None
示例#5
0
    def __init__(self):
        engine = csnd6.Csound()
        engine.SetOption("-odac")
        engine.Compile("player.csd")

        thread = csnd6.CsoundPerformanceThread(engine)
        thread.Play()

        self.engine = engine
        self.thread = thread
示例#6
0
 def __init__(self):
     self.loglines = []
     self.channelValues = {}
     self.activeSliders = []
     self.perf = None
     self.csound = csnd6.Csound()
     self.csdfile = None
     self.midiLearnSlider = None
     self.midiLearnEndFlag = False
     self.callbackPass = 0
示例#7
0
 def createEngine(self):
     self.cs = csnd6.Csound()
     res = self.cs.Compile('shapes.csd')
     if res == 0:
         self.cs.SetChannel('pitch', 1.0)
         self.cs.SetChannel('volume', 1.0)
         self.perf = csnd6.CsoundPerformanceThread(self.cs)
         self.perf.Play()
         return True
     else:
         return False
示例#8
0
    def start_engine(self,
                     sr=44100,
                     ksmps=64,
                     nchnls=2,
                     zerodbfs=1.0,
                     dacout='dac',
                     adcin=None,
                     port=None,
                     buffersize=None):
        ''' Start the csound engine on a separate thread'''
        if self._cs and self._csPerf:
            print("icsound: Csound already running")
            return
        if self._client_addr or self._client_port:
            self._client_addr = None
            self._client_port = None
            self._debug_print(
                "Closing existing client connection before starting engine")

        self._sr = sr
        self._ksmps = ksmps
        self._nchnls = nchnls
        self._0dbfs = zerodbfs
        self._dacout = dacout
        self._adcin = adcin
        self._cs = csnd6.Csound()
        self._cs.CreateMessageBuffer(0)
        self._cs.SetOption('-o' + self._dacout)
        self._buffersize = buffersize
        if self._adcin:
            self._cs.SetOption('-i' + self._adcin)
        if port:
            self._cs.SetOption("--port=%i" % port)
        if self._buffersize:
            self._cs.SetOption('-B' + str(self._buffersize))
            self._cs.SetOption('-b' + str(self._buffersize))
        self._cs.CompileOrc('''sr = %i
        ksmps = %i
        nchnls = %i
        0dbfs = %f
        ''' % (self._sr, self._ksmps, self._nchnls, self._0dbfs))
        self._cs.Start()
        self._csPerf = csnd6.CsoundPerformanceThread(self._cs)
        self._csPerf.Play()
        self._flush_messages()

        if (self._csPerf.GetStatus() == 0):
            print("Csound server started.")
            if port:
                print("Listening to port %i" % port)
        else:
            print("Error starting server. Maybe port is in use?")
示例#9
0
    def runForSyntaxCheck(self, csdfile):
        try:
            os.remove(os.path.join(TMP_PATH, 'csoundLog.txt'))
        except:
            pass
        CeciliaLib.setDayTime()
        self.logfile = open(os.path.join(TMP_PATH, 'csoundLog.txt'), 'w')

        cs = csnd6.Csound()
        cs.SetMessageCallback(self.logger)
        cs.Compile('--syntax-check-only', csdfile)

        self.logfile.close()
示例#10
0
    def __init__(self, volume, frequency):
        engine = csnd6.Csound()
        engine.SetOption("-odac")
        engine.Compile("osc.csd") 

        thread = csnd6.CsoundPerformanceThread(engine) 
        thread.Play()              

        self.engine = engine
        self.thread = thread

        self.set_volume(volume)
        self.set_frequency(frequency)
示例#11
0
def csound(memorize_q, ear_q, output, learn_state, respond_state):
    import csnd6
    cs = csnd6.Csound()
    cs.Compile("self_audio_csnd.csd")
    cs.Start()
    stopflag = 0
    #fft_audio_in1 = np.zeros(1024)
    #fft_audio_in2 = np.zeros(1024)
    offset = 0

    level1 = deque(maxlen=4000)
    envelope1 = deque(maxlen=4000)
    pitch1 = deque(maxlen=4000)
    centr1 = deque(maxlen=4000)

    while not stopflag:
        stopflag = cs.PerformKsmps()

        offset += 0.01
        offset %= 200
        cs.SetChannel("freq_offset", offset)
        #test1 = cs.GetPvsChannel(fft_audio_in1, 0)
        #test2 = cs.GetPvsChannel(fft_audio_in2, 1)

        # get Csound channel data
        #audioStatus = cs.GetChannel("audioStatus")
        level1.append(cs.GetChannel("level1"))
        envelope1.append(cs.GetChannel("envelope1"))
        pitch1.append(cs.GetChannel("pitch1"))
        centr1.append(cs.GetChannel("centroid1"))

        if learn_state.value:
            print '[self.] learns'
            memorize_q.put(np.asarray([level1, envelope1, pitch1, centr1]).T)
            learn_state.value = 0
        if respond_state.value:
            print '[self.] responds'
            ear_q.put(np.asarray([level1, envelope1, pitch1, centr1]).T)
            respond_state.value = 0

        try:
            response = output.pop(0)
            cs.SetChannel("respondLevel1", response[0])
            cs.SetChannel("respondEnvelope1", response[1])
            cs.SetChannel("respondPitch1", response[2])
            cs.SetChannel("respondCentroid1", response[3])
        except:
            cs.SetChannel("respondLevel1", 0)
            cs.SetChannel("respondEnvelope1", 0)
            cs.SetChannel("respondPitch1", 0)
            cs.SetChannel("respondCentroid1", 0)
示例#12
0
def main(c):

    cs = csnd6.Csound()
    res = cs.Compile(csoundFile)
    if res == 0:
        perf = csnd6.CsoundPerformanceThread(cs)
        perf.Play()

    switch_state = c.switches()
    switch_last = switch_state
    last_nobs = c.nobs()
    tolerance = 0.001
    first = True

    count = 0
    now = time()
    while True:
        nobs = c.nobs()
        changed = [abs(n - l) > tolerance for n, l in zip(nobs, last_nobs)]
        last_nobs = nobs

        for i, (nob, change) in enumerate(zip(nobs, changed)):
            if change or first:
                cs.SetChannel("P" + str(i), nob)
                print("{}: ".format(i) + "=" * int(nob * 80))

        switches = c.switches()
        posedge = [s and not l for s, l in zip(switches, switch_last)]
        changed = [s != l for s, l in zip(switches, switch_last)]
        switch_last = switches

        for i, edge in enumerate(posedge):
            if edge or first:
                switch_state[i] = not switch_state[i]
                cs.SetChannel("T" + str(i), switch_state[i])

        for i, change in enumerate(changed):
            if change or first:
                cs.SetChannel("M" + str(i), switches[i])

        leds = {}
        for i in range(c.nleds):
            leds[i] = cs.GetChannel("L" + str(i)) != 0
            #leds[i] = switch_state[i]
        c.set_leds(leds)

        now += 0.005
        safesleep(now - time())
        count += 1
        first = False
示例#13
0
    def __init__(self, master=None):  #Constructor
        Frame.__init__(self, master)

        self.Pack()
        self.create_widgets()
        self.orc = """
        sr = 44100
        ksmps = 32
        nchnls = 2
        0dbfs = 1

        instr set_cutoff
        kFreq init 200
        kFreq chnget "cutoff"
        SLoc chnget "loc"
        print 100
        aSig vco2 0.5, 80
        ;aSig, aSig diskin  SLoc
        aFilt moogladder aSig, kFreq, 0.5
        outs aFilt, aFilt
        endin

        

        instr set_resonance
        iRes init 0.5
        iRes chnget "res"
        SLoc chnget "loc"
        aSig vco2 0.5, 80
        ;aSig, aSig diskin SLoc
        aFilt moogladder aSig, 200, iRes
        outs aFilt, aFilt
        endin

        
        
        instr unused
        prints "running"
        endin
        """
        File_Dir = "D:\College\Test.wav"
        self.speak = wincl.Dispatch("SAPI.SpVoice")
        self.c = csnd6.Csound()
        self.c.SetOption("-odac")
        self.c.SetOption("-m7")
        self.c.CompileOrc(self.orc)
        self.c.ReadScore("""i"unused" 0 [60*60*24*7]""")
        self.c.Start()
        self.c.SetChannel("SLoc", File_Dir)
        self.c.Stop()  #ideally on stop button press
示例#14
0
 def __init__(self, master=None):
     master.title("Csound + Tkinter: just click and play")
     self.items = []
     self.notes = []
     Frame.__init__(self, master)
     self.pack()
     self.createCanvas()
     self.createShapes()
     self.cs = csnd6.Csound()
     res = self.cs.Compile("shapes.csd")
     self.cs.SetChannel("pitch", 1.0)
     self.cs.SetChannel("volume", 1.0)
     self.vu = []
     self.meter()
     master.after(100, self.draw),
     self.master = master
     self.perf = csnd6.CsoundPerformanceThread(self.cs)
     self.perf.Play()
     self.master.protocol("WM_DELETE_WINDOW", self.quit)
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()
        self.orc = """
        sr = 44100
        ksmps = 32
        nchnls = 2
        0dbfs = 1
        instr 1
        kFreq init 0
        kFreq chnget "cutoff"
        SLoc chnget "loc"
        aSig vco2 0.5, 80
        ;aSig, aSig diskin  SLoc
        aFilt moogladder aSig, kFreq, 0.5
        aFilt = aFilt
        outs aFilt, aFilt
        endin
        instr set_resonance
        iRes init 0
        iRes chnget "res"
        SLoc chnget "loc"
        aSig vco2 0.5, 80
        ;aSig, aSig diskin SLoc
        aFilt moogladder aSig, 200, iRes
        outs aFilt, aFilt
        endin     
        instr unused
        prints "running"
        endin
        """

        File_Dir = "D:\College\Test.wav"
        #self.speak = wincl.Dispatch("SAPI.SpVoice")
        self.c = csnd6.Csound()
        self.c.SetOption("-odac 1")
        self.c.SetOption("-m7")
        self.c.CompileOrc(self.orc)
        self.c.ReadScore(self.sco)
        self.c.SetChannel("SLoc", File_Dir)
示例#16
0
 def __init__(self, master=None):
     self.time = 0.0
     self.rectime = 0.0
     self.items = []
     self.notes = []
     self.notesrec = []
     self.recording = False
     self.playing = False
     Frame.__init__(self, master)
     self.pack()
     self.createCanvas()
     self.createKeys()
     self.cs = csnd6.Csound()
     res = self.cs.Compile("keys.csd")
     self.perf = csnd6.CsoundPerformanceThread(self.cs)
     self.perf.Play()
     self.master = master
     self.master.bind("<space>", self.record)
     self.master.bind("<Return>", self.playstop)
     self.master.protocol("WM_DELETE_WINDOW", self.quit)
     master.title("Keysplay vocoder")
示例#17
0
    def __init__(self):
        self._csnd = csnd6.Csound()
        self._csnd.CompileCsd(Config.PLUGIN_UNIVORC)
        self._csnd.SetDebug(False)
        self._csnd.Start()
        self._perfThread = csnd6.CsoundPerformanceThread(self._csnd)
        self._perfThread.Play()

        # TODO
        # sc_initialize(Config.PLUGIN_UNIVORC, Config.PLUGIN_DEBUG,
        #        Config.PLUGIN_VERBOSE, Config.PLUGIN_RATE)
        self.on = False
        self.setMasterVolume(100.0)
        self.periods_per_buffer = 2
        global _loop_default
        # TODO
        # _loop_default = self.loopCreate()
        self.instrumentDB = InstrumentDB.getRef()

        # temporyary dictionary of loopId: loopNumTicks,
        # while I wait for james to implement it properly
        self.jamesSux = {}
示例#18
0
文件: 11.2.py 项目: adsrLAB/book
 def __init__(self, master=None):
   # setup Csound
   self.cs = csnd6.Csound()
   self.cs.SetOption('-odac')
   if self.cs.CompileOrc('''
       instr 1
        a1 oscili p4, p5
        k1 expseg 1,p3,0.001
        out a1*k1*0dbfs
       endin
      ''') == 0:
    self.cs.Start()
    self.t = csnd6.CsoundPerformanceThread(self.cs)
    self.t.Play()
    # setup GUI
    tk.Frame.__init__(self, master)   
    tk.Frame.config(self, height=200, width=200)
    self.grid(ipadx=50, ipady=25)               
    self.Button = tk.Button(self, text='play',
     command=self.playSound)           
    self.Button.pack(padx=50, pady=50, fill='both')  
    self.master.protocol("WM_DELETE_WINDOW",
     self.quit)
    self.master.title('Beep')
示例#19
0
 def __init__(self):        
     self.engine = csnd6.Csound()
     self.start_csound()
     self.free_channel = 0
     self.free_loop_channel = 0
示例#20
0
orc = """
sr=44100
ksmps=32
nchnls=2
0dbfs=1

instr 1 
aout vco2 0.5, 440
outs aout, aout
endin"""

# Our Score for our project
sco = "i1 0 1"


c = csnd6.Csound()    # create an instance of Csound
c.SetOption("-odac")  # Set option for Csound
c.CompileOrc(orc)     # Compile Orchestra from String
c.ReadScore(sco)      # Read in Score from String
c.Start()             # When compiling from strings, this call is necessary before doing any performing

# The following is our main performance loop. We will perform one block of sound at a time 
# and continue to do so while it returns 0, which signifies to keep processing.  We will
# explore this loop technique in further examples.

while (c.PerformKsmps() == 0):
  pass

c.Stop()

示例#21
0
def csound(memorize_q, ear_q, output):
    import csnd6
    cs = csnd6.Csound()
    arguments = csnd6.CsoundArgVList()
    arguments.Append("dummy")
    arguments.Append("imitate_microphone2.csd")
    csoundCommandline = myCsoundAudioOptions.myAudioDevices
    comlineParmsList = csoundCommandline.split(' ')
    for item in comlineParmsList:
        arguments.Append("%s" % item)
    cs.Compile(arguments.argc(), arguments.argv())
    #cs.Start()
    stopflag = 0
    #fft_audio_in1 = np.zeros(1024)
    #fft_audio_in2 = np.zeros(1024)
    offset = 0

    level1 = deque(maxlen=4000)
    envelope1 = deque(maxlen=4000)
    pitch1 = deque(maxlen=4000)
    centr1 = deque(maxlen=4000)

    i = 0
    somethingLearned = 0
    learnStatus = 0
    imitateStatus = 0

    while not stopflag:
        stopflag = cs.PerformKsmps()

        offset += 0.01
        offset %= 200
        cs.SetChannel("freq_offset", offset)
        #test1 = cs.GetPvsChannel(fft_audio_in1, 0)
        #test2 = cs.GetPvsChannel(fft_audio_in2, 1)

        # get Csound channel data
        audioStatus = cs.GetChannel("audioStatus")
        level1.append(cs.GetChannel("level1"))
        envelope1.append(cs.GetChannel("envelope1"))
        pitch1.append(cs.GetChannel("pitch1"))
        centr1.append(cs.GetChannel("centroid1"))

        if (audioStatus - learnStatus) < 0: imitateTrig = 1
        else: imitateTrig = 0
        learnStatus = audioStatus
        if learnStatus > 0: somethingLearned = 1
        if somethingLearned:
            imitateStatus = 1 - learnStatus

        i += 1
        if learnStatus and ((i % 1000)
                            == 0):  # if something is happening on audio input
            memorize_q.put(np.asarray([level1, envelope1, pitch1, centr1]).T)

        # will make a response when the audio input segment (sentence) is done
        # however, now it seems to continue playback even if a new sentence starts at audio input
        # it might be nice if it would (optionally?) stop talking when new audio input arrives
        if imitateStatus and imitateTrig:
            ear_q.put(np.asarray([level1, envelope1, pitch1, centr1]).T)

        try:
            imitation = output.pop(0)
            cs.SetChannel("imitateLevel1", imitation[0])
            cs.SetChannel("imitateEnvelope1", imitation[1])
            cs.SetChannel("imitatePitch1", imitation[2])
            cs.SetChannel("imitateCentroid1", imitation[3])
        except:
            cs.SetChannel("imitateLevel1", 0)
            cs.SetChannel("imitateEnvelope1", 0)
            cs.SetChannel("imitatePitch1", 0)
            cs.SetChannel("imitateCentroid1", 0)
示例#22
0
# Example 1 - Simple Compilation with Csound
# Author: Steven Yi <*****@*****.**>
# 2013.10.28
#
# This example is a barebones example for creating an instance of Csound, 
# compiling a pre-existing CSD, calling Perform to run Csound to completion,
# then Stop and exit.  

# The first thing we do is import the csnd6 module, which is the module 
# containing the Python interface to the Csound API.

import csnd6

c = csnd6.Csound()        # Create an instance of the Csound object
c.Compile('test1.csd')    # Compile a pre-defined test1.csd file
c.Perform()               # This call runs Csound to completion
c.Stop()                  # At this point, Csound is already stopped, but this call is here
                          # as it is something that you would generally call in real-world 
                          # contexts 

示例#23
0
ksmps = 10
nchnls = 1

; Instrument #1.
instr 1000
   kamp = 30000
   kcps = 1
   ifn = 10
   ibas = 1

   ; Play the audio sample stored in Table #1.
   a1 loscil kamp, kcps, ifn, ibas
   out a1
endin"""

c = csnd6.Csound()
c.SetOption("-odac")
c.CompileOrc(orc)
c.Start()

# the first parameter should be the same as the ifn value in the instrument
c.InputMessage('f 10 0 131072 1 "beats.wav" 0 4 0')

perfThread = csnd6.CsoundPerformanceThread(c)
perfThread.Play()


def clicked_cb(button, c):
    python_array = [
        1000,  # this need be the instrument number
        0.0,
示例#24
0
 def load_csound_server(self, port):
     c = csnd6.Csound()        
     self.engine = c
示例#25
0
文件: IO.py 项目: afcarl/self_dot
def audio():
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.bind('tcp://*:{}'.format(MIC))

    robocontrol = context.socket(zmq.PUSH)
    robocontrol.connect('tcp://localhost:{}'.format(ROBO))

    subscriber = context.socket(zmq.PULL)
    subscriber.bind('tcp://*:{}'.format(SPEAKER))

    stateQ = context.socket(zmq.SUB)
    stateQ.connect('tcp://localhost:{}'.format(STATE))
    stateQ.setsockopt(zmq.SUBSCRIBE, b'') 

    eventQ = context.socket(zmq.SUB)
    eventQ.connect('tcp://localhost:{}'.format(EVENT))
    eventQ.setsockopt(zmq.SUBSCRIBE, b'') 

    sender = context.socket(zmq.PUSH)
    sender.connect('tcp://localhost:{}'.format(EXTERNAL))

    poller = zmq.Poller()
    poller.register(subscriber, zmq.POLLIN)
    poller.register(stateQ, zmq.POLLIN)
    poller.register(eventQ, zmq.POLLIN)

    memRecPath = myCsoundAudioOptions.memRecPath

    import csnd6
    cs = csnd6.Csound()

    arguments = csnd6.CsoundArgVList()
    
    arguments.Append("dummy")
    arguments.Append("self_dot.csd")
    csoundCommandline = myCsoundAudioOptions.myAudioDevices
    
    comlineParmsList = csoundCommandline.split(' ')
    for item in comlineParmsList:
        arguments.Append("%s"%item)
    cs.Compile(arguments.argc(), arguments.argv())

    stopflag = 0
    zeroChannelsOnNoBrain = 1

    # optimizations to avoid function lookup inside loop
    tGet = cs.TableGet 
    tSet = cs.TableSet
    cGet = cs.GetChannel
    cSet = cs.SetChannel
    perfKsmps = cs.PerformKsmps

    filename = []
    counter = 0
    ampPitchCentroid = [[],[],[]]
    
    ambientFiles = [] # used by the ambient sound generator (instr 90 pp)
    ambientActive = 0
    prev_i_am_speaking = 0
    skip_file = 0
    recalibrate_timer_enable = True
    recalibrate_time = 120
    time_last_recorded = time.time()

    state = stateQ.recv_json()
    
    while not stopflag:
        counter += 1
        counter = counter%16000 # just to reset sometimes
        stopflag = cs.PerformKsmps()

        events = dict(poller.poll(timeout=0))

        if stateQ in events:
            state = stateQ.recv_json()

        # get Csound channel data
        audioStatus = cGet("audioStatus")           
        audioStatusTrig = cGet("audioStatusTrig")       # signals start of a statement (audio in)
        transient = cGet("transient")                   # signals start of a segment within a statement (audio in)        
        memRecTimeMarker = cGet("memRecTimeMarker")     # (in memRec) get (active record) the time since start of statement
        memRecSkiptime = cGet("memRecSkiptime")         # (in memRec) get the time (amount) of stripped sielence) in the latest segment
        memRecActive = cGet("memRecActive")             # flag to check if memoryRecording is currently recording to file in Csound
        memRecMaxAmp = cGet("memRecMaxAmp")             # max amplitude for each recorded file
        statusRel = cGet("statusRel")                   # audio status release time 
        noiseFloor = cGet("inputNoisefloor")            # measured noise floor in dB
        too_long_segment = cGet("too_long_segment")     # signals a segment that is longer thant we like
        too_long_sentence = cGet("too_long_sentence")     # signals a sentence that is longer thant we like
        
        i_am_speaking = cGet("i_am_speaking")           # signals cognition that I'm currently speaking
        cSet("i_am_speaking", 0)                        # reset channel, any playing voice instr will overwrite
        if i_am_speaking != prev_i_am_speaking:         # send if changed
            sender.send_json('i_am_speaking {}'.format(int(i_am_speaking)))
        prev_i_am_speaking = i_am_speaking
        
        panposition = cs.GetChannel("panalyzer_pan")
        in_amp = cs.GetChannel("followdb") #rather use envelope follower in dB than pure rms channel "in_amp")
        in_pitch = cs.GetChannel("in_pitch")
        in_centroid = cs.GetChannel("in_centroid")
        
        if state['roboActive'] > 0:
            if (panposition < 0.48) or (panposition > 0.52):
                print 'panposition', panposition
                robocontrol.send_json([1,'pan',panposition-.5])
            if (counter % 500) == 0:
                robocontrol.send_json([2,'pan',-1])
         
        if state['ambientSound'] > 0:
            if ambientActive == 0:
                cs.InputMessage('i 92 0 -1')
                ambientActive = 1
            if (counter % 4000) == 0:
                newtable, ambientFiles = utils.updateAmbientMemoryWavs(ambientFiles)
                cs.InputMessage('i 90 0 4 "%s"'%newtable)
        
        if state['ambientSound'] == 0:
            if ambientActive == 1:
                cs.InputMessage('i -92 0 1')
                ambientActive = 0
        
        if state['memoryRecording']:
            if audioStatusTrig > 0:
                skip_file = 0
                timestr = time.strftime('%Y_%m_%d_%H_%M_%S')
                print 'starting memoryRec', timestr
                tim_time = time.time()
                filename = memRecPath+timestr+'.wav'
                time_frac = tim_time-int(tim_time)
                instrNum = 34+time_frac
                cs.InputMessage('i %f 0 -1 "%s"'%(instrNum,filename))
                markerfileName = memRecPath+timestr+'.txt'
                markerfile = open(markerfileName, 'w')
                markerfile.write('Self. audio clip perceived at %s\n'%tim_time)
                segmentstring = 'Sub segments (start, skiptime, amp, pitch, cent): \n'
                segStart = 0.0
                ampPitchCentroid = [[],[],[]]
            if audioStatus > 0:
                ampPitchCentroid[0].append(in_amp)
                ampPitchCentroid[1].append(in_pitch)
                ampPitchCentroid[2].append(in_centroid)
            if (transient > 0) & (memRecActive > 0):
                if memRecTimeMarker == 0: pass
                else:
                    print '... ...get medians and update segments'
                    ampPitchCentroid[0].sort()
                    l = ampPitchCentroid[0]
                    ampMean = max(l)
                    ampPitchCentroid[1].sort()
                    l = ampPitchCentroid[1]
                    pitchMean = np.mean(l[int(len(l)*0.25):int(len(l)*0.75)])
                    ampPitchCentroid[2].sort()
                    l = ampPitchCentroid[2]
                    centroidMean = np.mean(l[int(len(l)*0.25):int(len(l)*0.9)])
                    ampPitchCentroid = [[],[],[]]
                    segmentstring += '%.3f %.3f %.3f %.3f %.3f\n'%(segStart,memRecSkiptime,ampMean,pitchMean,centroidMean)
                    segStart = memRecTimeMarker 
            if (audioStatusTrig < 0) & (memRecActive > 0):
                print '... ...get final medians and update segments'
                ampPitchCentroid[0].sort()
                l = ampPitchCentroid[0]
                ampMean = max(l)
                ampPitchCentroid[1].sort()
                l = ampPitchCentroid[1]
                pitchMean = np.mean(l[int(len(l)*0.25):int(len(l)*0.75)])
                ampPitchCentroid[2].sort()
                l = ampPitchCentroid[2]
                centroidMean = np.mean(l[int(len(l)*0.25):int(len(l)*0.9)])
                ampPitchCentroid = [[],[],[]]
                segmentstring += '%.3f %.3f %.3f %.3f %.3f\n'%(segStart,memRecSkiptime-statusRel,ampMean,pitchMean,centroidMean) #normal termination of recording, we should subtract statusRel from last skiptime
                #segmentstring += '%.3f %.3f %.3f %.3f %.3f\n'%(segStart,memRecSkiptime,ampMean,pitchMean,centroidMean) 
                segmentlist = segmentstring.split('\n')
                segmentlist.pop() # ditch the empty list item at the end
                markertablist = []
                markerTempTab = cGet("giMarkerTemp")
                for i in range(32):
                    markertime = tGet(int(markerTempTab), i)
                    markertablist.append(markertime)
                segmentstring = '{}\n'.format(segmentlist.pop(0))
                total_segment_time = 0.0
                skip_time = 0.0
                skip_count = 0
                skip_file = 0
                for i in range(len(segmentlist)):
                    segmentlist[i] = segmentlist[i].split(' ')
                print 'markertablist', markertablist
                print 'segmentlist',segmentlist
                
                for i in range(len(segmentlist)):
                    if markertablist[i] < 0 :
                        #print 'SKIPPING \n  SEGMENT \n    {}'.format(segmentlist[i])
                        skip_count += 1
                        if skip_count >= len(segmentlist): 
                            skip_file = 1
                            print 'SKIPPING EMPTY FILE at time {}'.format(timestr) 
                        if i<len(segmentlist)-1:
                            skip_time += float(segmentlist[i+1][0])-float(segmentlist[i][0])
                        else:
                            skip_time += memRecTimeMarker-float(segmentlist[i][0])
                    else:
                        segmentlist[i][0] = '%.3f'%total_segment_time
                        segment_n = ''
                        for item in segmentlist[i]: segment_n += str(item) + ' '
                        segment_n = segment_n.rstrip(' ')
                        segmentstring += segment_n+'\n'
                        if i<len(segmentlist)-1:
                            total_segment_time = float(segmentlist[i+1][0])-skip_time
                        else:
                            total_segment_time = memRecTimeMarker-skip_time
                #print 'segmentstring\n', segmentstring
                cs.InputMessage('i -%f 0 1'%instrNum)
                markerfile.write(segmentstring)
                markerfile.write('Total duration: %f\n'%total_segment_time)
                markerfile.write('\nMax amp for file: %f'%memRecMaxAmp)
                markerfile.close()
                print 'stopping memoryRec'            
            
            if too_long_segment > 0 or too_long_sentence > 0:
                for i in range(20):
                    print ' '*i, '*'*i
                if too_long_segment > 0:
                    print "TOO LONG SEGMENT"
                else:
                    print "TOO LONG SENTENCE"
                cs.InputMessage('i -%f 0 1'%instrNum)
                skip_file = 1
                cSet("too_long_segment", 0)
                cSet("too_long_sentence", 0)
                cSet("memRecActive", 0)
                memRecActive = 0
                sender.send_json('_audioLearningStatus 0')
                sender.send_json('stoprec')
                sender.send_json('calibrateAudio')
                
        if not state['memoryRecording'] and memRecActive:
            print '... ...turnoff rec, get final medians and update segments'
            ampPitchCentroid[0].sort()
            l = ampPitchCentroid[0]
            ampMean = max(l)
            ampPitchCentroid[1].sort()
            l = ampPitchCentroid[1]
            pitchMean = np.mean(l[int(len(l)*0.25):int(len(l)*0.75)])
            ampPitchCentroid[2].sort()
            l = ampPitchCentroid[2]
            centroidMean = np.mean(l[int(len(l)*0.25):int(len(l)*0.9)])
            ampPitchCentroid = [[],[],[]]
            segmentstring += '%.3f %.3f %.3f %.3f %.3f\n'%(segStart,memRecSkiptime-statusRel,ampMean,pitchMean,centroidMean) #normal termination of recording, we should subtract statusRel from last skiptime
            #segmentstring += '%.3f %.3f %.3f %.3f %.3f\n'%(segStart,memRecSkiptime,ampMean,pitchMean,centroidMean) 
            segmentlist = segmentstring.split('\n')
            segmentlist.pop() # ditch the empty list item at the end
            markertablist = []
            for i in range(32):
                markertime = tGet(int(markerTempTab), i)
                markertablist.append(-1) #hard and dirty, skip all if we turn off memory recording while recording a sentence
            segmentstring = '{}\n'.format(segmentlist.pop(0))
            total_segment_time = 0.0
            skip_time = 0.0
            skip_count = 0
            skip_file = 0
            for i in range(len(segmentlist)):
                segmentlist[i] = segmentlist[i].split(' ')
            print 'markertablist', markertablist
            print 'segmentlist',segmentlist
            
            for i in range(len(segmentlist)):
                if markertablist[i] < 0 :
                    print 'SKIPPING \n  SEGMENT \n    {}'.format(segmentlist[i])
                    skip_count += 1
                    if skip_count >= len(segmentlist): 
                        skip_file = 1
                        print 'SKIPPING EMPTY FILE at time {}'.format(timestr) 
                    if i<len(segmentlist)-1:
                        skip_time += float(segmentlist[i+1][0])-float(segmentlist[i][0])
                    else:
                        skip_time += memRecTimeMarker-float(segmentlist[i][0])
                else:
                    segmentlist[i][0] = '%.3f'%total_segment_time
                    segment_n = ''
                    for item in segmentlist[i]: segment_n += str(item) + ' '
                    segment_n = segment_n.rstrip(' ')
                    segmentstring += segment_n+'\n'
                    if i<len(segmentlist)-1:
                        total_segment_time = float(segmentlist[i+1][0])-skip_time
                    else:
                        total_segment_time = memRecTimeMarker-skip_time
            print 'segmentstring\n', segmentstring
            cs.InputMessage('i -%f 0 1'%instrNum)
            markerfile.write(segmentstring)
            markerfile.write('Total duration: %f\n'%total_segment_time)
            markerfile.write('\nMax amp for file: %f'%memRecMaxAmp)
            markerfile.close()
            print 'stopping memoryRec'

        interaction = []
        
        if (state['autolearn'] or state['autorespond_single'] or state['autorespond_sentence']) and not skip_file:
            if audioStatusTrig > 0:
                sender.send_json('startrec')
                sender.send_json('_audioLearningStatus 1')
                time_last_recorded = time.time()
                recalibrate_timer_enable = True
            if audioStatusTrig < 0:
                sender.send_json('stoprec')
                sender.send_json('_audioLearningStatus 0')
                time_last_recorded = time.time()
                recalibrate_timer_enable = True
                if filename:
                    if state['autolearn']:
                        interaction.append('learnwav {}'.format(os.path.abspath(filename)))
                    if state['autorespond_single']:
                        interaction.append('respondwav_single {}'.format(os.path.abspath(filename)))
                    if state['autorespond_sentence']:
                        interaction.append('respondwav_sentence {}'.format(os.path.abspath(filename)))
        if (time.time()-time_last_recorded > recalibrate_time) and recalibrate_timer_enable:
            for i in range(20):
                print ' '*(20-i), '*'*(20-i)
            sender.send_json('calibrateAudio')
            recalibrate_timer_enable = False
                

        if interaction and not skip_file:
            sender.send_json('calculate_cochlear {}'.format(os.path.abspath(filename)))

            for command in interaction:
                sender.send_json(command)

        if eventQ in events:
            pushbutton = eventQ.recv_json()
            if 'selfvoice' in pushbutton:
                    print 'not implemented'

            if 'inputLevel' in pushbutton:
                mode = pushbutton['inputLevel']
                if mode == 'mute':
                    cs.InputMessage('i 21 0 .1 0')
                    print 'Mute'
                if mode == 'unmute':
                    cs.InputMessage('i 21 0 .1 1')
                    print 'Un-mute'
                if mode == 'reset': 
                    cs.InputMessage('i 21 0 .1 0')
                    cs.InputMessage('i 21 1 .1 1')

            if 'calibrateEq' in pushbutton:
                cs.InputMessage('i -99 0 1') # turn off master out
                cs.InputMessage('i 19 0.5 2') # eq profiling
                cs.InputMessage('i 99 3 -1') # turn on master out

            if 'setLatency' in pushbutton:
                value = pushbutton['setLatency']
                cSet("audio_io_latency",value) 
                print 'Csound roundtrip latency set to {}'.format(cGet("audio_io_latency"))

            if 'calibrateAudio' in pushbutton:
                cs.InputMessage('i -17 0 1') # turn off old noise gate
                cs.InputMessage('i 12 0 3.9') # measure roundtrip latency
                cs.InputMessage('i 13 4 1.9') # get audio input noise print
                cs.InputMessage('i 14 6 -1') # enable noiseprint and self-output suppression
                cs.InputMessage('i 15 6.2 2') # get noise floor level 
                cs.InputMessage('i 16 8.3 0.1') # set noise gate shape
                cs.InputMessage('i 17 8.5 -1') # turn on new noise gate
                                               
            if 'calibrateNoiseFloor' in pushbutton:
                cs.InputMessage('i -17 0 .1') # turn off old noise gate
                cs.InputMessage('i -14 0 .1') # turn off noiseprint and self-output suppression
                cs.InputMessage('i 13 .3 1.5') # get audio input noise print
                cs.InputMessage('i 14 2 -1') # enable noiseprint and self-output suppression
                cs.InputMessage('i 15 2.2 1.5') # get noise floor level 
                cs.InputMessage('i 16 3.9 0.1') # set noise gate shape
                cs.InputMessage('i 17 4 -1') # turn on new noise gate

            if 'csinstr' in pushbutton:
                # generic csound instr message
                cs.InputMessage('{}'.format(pushbutton['csinstr']))
                print 'sent {}'.format(pushbutton['csinstr'])

            if 'selfDucking' in pushbutton:
                value = pushbutton['selfDucking']
                cs.InputMessage('i 22 0 1 "selfDucking" %f'%float(value))

            if 'zerochannels' in pushbutton:
                zeroChannelsOnNoBrain = int('{}'.format(pushbutton['zerochannels']))

            if 'playfile' in pushbutton:
                #print '[self.] AUDIO playfile {}'.format(pushbutton['playfile'])
                try:
                    params = pushbutton['playfile']
                    voiceChannel, voiceType, start, soundfile, speed, segstart, segend, amp, maxamp = params.split(' ')
                    soundfile = str(soundfile)
                    voiceChannel = int(voiceChannel) # internal or external voice (primary/secondary associations)
                    instr = 60 + int(voiceType)
                    start = float(start)
                    segstart = float(segstart)
                    segend = float(segend)
                    amp = float(amp)
                    maxamp = float(maxamp)
                    speed = float(speed)
                    if voiceChannel == 2:
                        delaySend = -26 # delay send in dB
                        reverbSend = -23 # reverb send in dB
                    else:
                        delaySend = -96
                        reverbSend = -96 
                    csMessage = 'i %i %f 1 "%s" %f %f %f %f %i %f %f %f' %(instr, start, soundfile, segstart, segend, amp, maxamp, voiceChannel, delaySend, reverbSend, speed)
                    #print 'csMessage', csMessage                 
                    cs.InputMessage(csMessage)

                except Exception, e:
                    print e, 'Playfile aborted.'
示例#26
0
文件: 2.11.py 项目: adsrLAB/book
import csnd6
import sys

csound = csnd6.Csound()
args = csnd6.CsoundArgVList()
for arg in sys.argv:
    args.Append(arg)

error = csound.Compile(args.argc(), args.argv())

while (not error):
    error = csound.PerformKsmps()