示例#1
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()
示例#2
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"""
示例#3
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()
示例#4
0
 def start_csound(self):
     c = self.engine
     c.SetOption("-odac")
     c.Compile('simpler.csd')
     #c.Start()
     perf_thread = csnd6.CsoundPerformanceThread(c)
     perf_thread.Play()
     self.perf_thread = perf_thread
示例#5
0
 def start_csound(self):
     if self.start_csound_flag:
         c = self.engine
         c.SetOption("--omacro:PORT=%d" % self.port_out)
         c.Compile('flow.csd')
         c.Start()
         perfThread = csnd6.CsoundPerformanceThread(c)
         perfThread.Play()
         self.perfThread = perfThread
示例#6
0
    def startCsound(self, csdfile):
        self.csdfile = csdfile
        self.loglines = []
        self.channelValues = {}
        self.activeSliders = []
        self.callbackPass = 0
        plugins = CeciliaLib.getPlugins()

        for slider in CeciliaLib.getSamplerSliders():
            if slider.getPlay():
                self.channelValues[slider.getCName()] = -999999999
        for slider in CeciliaLib.getUserSliders():
            if slider.getPlay(
            ) or slider.getMidiCtl() != None or slider.getWithOSC():
                self.activeSliders.append(slider)
                self.channelValues[slider.getName()] = -999999999
        for plug in plugins:
            if plug != None:
                for knob in plug.getKnobs():
                    if knob.getPlay() or knob.getMidiCtl() != None:
                        self.activeSliders.append(knob)
                        self.channelValues[knob.getName()] = -999999999

        res = self.csound.Compile(self.csdfile)
        if res == 0:
            self.call = Callback(0.075, self.callback)
            self.call.start()
            self.perf = csnd6.CsoundPerformanceThread(self.csound)
            self.perf.Play()
            if CeciliaLib.getGainSlider():
                self.setChannel('masterVolume',
                                CeciliaLib.getGainSlider().GetValue())
                plugins = CeciliaLib.getPlugins()
                for plug in plugins:
                    if plug != None:
                        plug.initCsoundChannels()
            for slider in CeciliaLib.getSamplerSliders():
                self.setChannel('%s_value' % slider.getCName(),
                                slider.getValue())
            for slider in CeciliaLib.getUserSliders():
                if type(slider.getValue()) in [ListType, TupleType]:
                    self.setChannel('%s_value_min' % slider.getName(),
                                    slider.getValue()[0])
                    self.setChannel('%s_value_max' % slider.getName(),
                                    slider.getValue()[1])
                else:
                    self.setChannel('%s_value' % slider.getName(),
                                    slider.getValue())
            for togPop in CeciliaLib.getUserTogglePopups():
                if togPop.getRate() != 'table':
                    self.setChannel('%s_value' % togPop.getName(),
                                    togPop.getValue())
        else:
            CeciliaLib.stopCeciliaSound()
            self.runForSyntaxCheck(self.csdfile)
            self.AnalyseLogFile(csnd6.csoundCfgErrorCodeToString(res))
示例#7
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
示例#8
0
    def Open(self, csdFile):
        print("CSoundPort:Open")
        self.startTime = datetime.datetime.now()
        if (csdFile is None):
            res = self.csound.CompileCsdText(defaultCSD)
        else:
            res = self.csound.Compile(csdFile)

        self.performance = csnd6.CsoundPerformanceThread(self.csound)
        self.csound.Start()
        self.performance.Play()
示例#9
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
示例#10
0
def start():
    global th
    cs.SetOption("-odac")
    cs.SetMessageLevel(0)
    cs.CompileOrc(params)
    cs.CompileOrc(player)
    cs.Start()
    th = csnd6.CsoundPerformanceThread(cs)
    th.Play()
    cs.CompileOrc(cycle.format(""))
    cs.CompileOrc("schedule 1,0,1,0")
示例#11
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?")
示例#12
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)
示例#13
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
示例#14
0
 def playThreadRoutine(self):
     try:
         print 'playThreadRoutine...'
         self.updateModel()
         self.csound.setOrchestra(self.configuration.orchestra)
         self.csound.setScore(self.configuration.score)
         self.csound.setCommand(self.configuration.command)
         self.csound.exportForPerformance()
         self.csound.compile()
         self.updateModel()
         self.csoundPerformanceThread = csnd6.CsoundPerformanceThread(
             self.csound)
         self.csoundPerformanceThread.Play()
         print 'Playing...'
     except:
         traceback.print_exc()
示例#15
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)
示例#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 csoundThreadRoutine(self):
     # Embed an orchestra in this script.
     self.csound.setOrchestra('''
         sr=44100
         ksmps=128
         nchnls=2
             instr   1
             ; print p1, p2, p3, p4, p5
             ; Slider sends note with MIDI key number.
             ; Convert it to octaves.
             ioctave = p4 / 12.0 + 3.0
             print ioctave
             ; Convert octave to frequency.
             ihertz = cpsoct(ioctave)
             p3 = p3 + 0.05
         a1  oscili  ampdb(p5), ihertz, 1
             kenv linseg 0, 0.05, 1, p3, 0
             a1 = kenv * a1
             outs    a1,a1
             endin
         ''')
     # And a score.
     self.csound.setScore('''
         f1 0 8192 10 1
         f0 600
         e
         ''')
     # Real-time audio output.
     # It is not necessary to enable line events.
     self.csound.setCommand(
         '''csound -h -m128 -d -odac -B512 -b400 temp.orc temp.sco''')
     # Export the orc and sco.
     self.csound.exportForPerformance()
     # Start the performance.
     self.csound.compile()
     # Perform in blocks of ksmps
     # (Csound will yield implicitly to wxWindows).
     self.performanceThread = csnd6.CsoundPerformanceThread(self.csound)
     self.performanceThread.Play()
示例#18
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 = {}
示例#19
0
    def midiLearn(self, slider, rangeSlider=False):
        if self.isCsoundRunning():
            CeciliaLib.showErrorDialog(
                "Csound is already started!",
                "Stop Csound before running Midi learn.")

        if rangeSlider:
            self.rangeCtrl = []
            self.rangeChan = []
        res = self.csound.Compile(
            os.path.join(RESOURCES_PATH + "/getMidiCtl.csd"))
        if res == 0:
            self.midiLearnEndFlag = True
            self.midiLearnSlider = slider
            self.call = Callback(0.075, self.midiLearnCallback, rangeSlider)
            self.call.start()
            self.perf = csnd6.CsoundPerformanceThread(self.csound)
            self.perf.Play()
            wx.CallLater(30000, self.checkMidiLearnEnd)
        else:
            CeciliaLib.showErrorDialog(
                "Abort Csound...",
                "Be sure there is a valid Midi interface connected!")
示例#20
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')
示例#21
0
   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,
        2.0
    ]
    csnd_array = csnd6.doubleArray(len(python_array))
    for n in range(len(python_array)):
        csnd_array[n] = python_array[n]
    print(python_array)
    c.ScoreEvent('i', csnd_array, len(python_array))
    # TODO: these are to try avoid seg fault at activity close (not enough)
示例#22
0
        chn = self.data[2]
        cs.ChanOAGet(chn.cast(), 1)
        for i in range(0, cs.GetKsmps()):
            sig.append(chn[i] / norm)
        disp.draw(sig, time_interval * cs.GetSr())

    def __init__(self, data):
        self.data = data


# create & compile instance
cs = csnd6.Csound()
cs.Compile("am.csd")

# create the thread object
perf = csnd6.CsoundPerformanceThread(cs)

# display object
master = Tk()
disp = display.Oscilloscope(master, window_size, perf.Stop, "green", "black")

# samples array
chn = csnd6.floatArray(cs.GetKsmps())
dat = (cs, disp, chn)
tes = Disp(dat)

# set the callback
perf.SetProcessCallback(tes.callb, None)

# play
perf.Play()