コード例 #1
0
        /* Example 3 - Using our own performance loop
        *
        * In this example, we use a while loop to perform Csound one audio block at a time.
        * This technique is important to know as it will allow us to do further processing
        * safely at block boundaries.  We will explore the technique further in later examples.
        *
        * The C# version includes checking the status code which csound returns after key processing.
        * These codes are encapsulated in the CsoundStatus enumeration.
        * This demonstrates the traditional way to respond to csound compiling and performing
        */
        public void Example3()
        {
            const string sco = "i1 0 1\n";
            using (var c = new Csound6Net())
            {
                //You can also set the output file or device using SetOutputFileName method in the API
                // SetOutputFileName(string path, SoundFileType type, SampleFormat format)
                // or its convenience method for real time output SetOutputDac(int dacNbr)
                // instead of via command line arguments fed to SetOption(string option) one at a time
                c.SetOutputDac(0);

                var status = c.CompileOrc(orc);      // Compile Orchestra from String
                if (status == CsoundStatus.Success)  // Classic csound practice tests compile results before proceeding
                {
                    status = c.ReadScore(sco);       // Read in Score from String variable
                    if (status == CsoundStatus.Success)
                    {
                        c.Start(); // When compiling from strings, this call needed before 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 false, which tells us to keep processing.
                         * We will explore this loop technique in further examples.
                         */
                        while (!c.PerformKsmps());

                        c.Stop();
                    }
                }
            }
        }
コード例 #2
0
        /* Example 3 - Using our own performance loop
        *
        * In this example, we use a while loop to perform Csound one audio block at a time.
        * This technique is important to know as it will allow us to do further processing
        * safely at block boundaries.  We will explore the technique further in later examples.
        *
        * The C# version includes checking the status code which csound returns after key processing.
        * These codes are encapsulated in the CsoundStatus enumeration.
        * This demonstrates the traditional way to respond to csound compiling and performing
        */
        public void Example3()
        {
            const string sco = "i1 0 1\n";
            using (var c = new Csound6Net())
            {
                c.SetOption("-odac");   // Set option for Csound
                var status = c.CompileOrc(orc);      // Compile Orchestra from String
                if (status == CsoundStatus.Success)  // Classic csound practice tests compile results before proceeding
                {
                    status = c.ReadScore(sco);       // Read in Score from String variable
                    if (status == CsoundStatus.Success)
                    {
                        c.Start(); // When compiling from strings, this call needed before 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 false, which tells us to keep processing.
                         * We will explore this loop technique in further examples.
                         */
                        while (!c.PerformKsmps());

                        c.Stop();
                    }
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Entry point to this command line version of Csound using a .net wrapper.
        /// It demonstrates how to emulate csound_main.c command line example provided
        /// with csound.
        /// Use exactly as one would use csound from a command prompt using all the same flags
        /// (well, the command itself would be different: "csound6net" instead of "csound".
        /// </summary>
        /// <param name="args">Parsed command line arguments </param>
        /// <returns>0 if successful, a negative csound error code if failed</returns>
        public static int Main(string[] args)
        {
            //Determine which log output we want prior to creating Csound6Net
            //so we can capture every csound message including initialization chatter.
            string path = FindLoggingPath(args);

            if ("NULL".Equals(path.ToUpper()))
            {
                _writer = null;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(path) || "stdout".Equals(path.ToLower()))
                {
                    _writer = Console.Out;
                }
                else
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    _writer = new StreamWriter(path, true);
                }
            }

            //Main Csound loop with ^c intercept
            CsoundStatus result;

            using (var csound = new Csound6Net(LoggingMessageHandler))
            {
                bool playing = true;//flag to capture ^c events and exit gracefully
                Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
                { e.Cancel = true;
                  playing = false; };

                result = playing ? csound.Compile(args) : CsoundStatus.TerminatedBySignal;

                if (result == CsoundStatus.Success)
                {
                    while (playing && !csound.PerformKsmps())
                    {
                        ;                                     //continue output until score is done or ^c is encountered
                    }
                }
            }

            //When done, shut down any logging that might be active
            if (_writer != null)
            {
                _writer.Flush();
                if (_writer != Console.Out)
                {
                    _writer.Dispose();
                }
            }
            return((((int)result) >= 0) ? 0 : (int)result);
        }
コード例 #4
0
 /* Example 1 - Simple Compilation with Csound
  *
  * This 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.
  * Resulting wave file will be found in the current directory or in SFDIR if established
  */
 public void Example1()
 {
     // Create an instance of the Csound object within a using block
     using (var c = new Csound6Net())             // Create an instance of the Csound object within a using block
     {
         c.Compile(new string[] { "test1.csd" }); // Compile a pre-defined test1.csd file, includes Start()
         c.Perform();                             // This call runs Csound to completion (saving Stop() for next example)
     }
     //c.Dispose() shuts csound down properly. It is called automatically as a "using" block exits.
 }
コード例 #5
0
 /* Example 1 - Simple Compilation with Csound
  *
  * This 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.
  * Resulting wave file will be found in the current directory or in SFDIR if established
  */
 public void Example1()
 {
     // Create an instance of the Csound object within a using block
     using (var c = new Csound6Net())// Create an instance of the Csound object within a using block
     {
         c.Compile(new string[] { "test1.csd" });  // Compile a pre-defined test1.csd file, includes Start()
         c.Perform();        // This call runs Csound to completion (saving Stop() for next example)
     }
     //c.Dispose() shuts csound down properly. It is called automatically as a "using" block exits.
 }
コード例 #6
0
        public void TestTableAccess()
        {
            Csound6Net   cs     = new Csound6Net();
            FileInfo     csf    = new FileInfo(@"csdFiles\xanadu.csd");
            CsoundStatus result = cs.CompileArgs(new string[] { csf.FullName });

            Assert.IsTrue(((int)result) >= 0);
            Assert.AreEqual(CsoundStatus.Success, cs.Start()); //CompileArgs doesn't call start();
            bool done = cs.PerformKsmps();                     //enough to get f1 to be created

            Assert.IsFalse(done);
            Csound6Table f1 = new Csound6Table(1, cs);

            Assert.IsTrue(f1.IsDefined);
            int len = f1.Length;

            Assert.AreEqual(8192, len); //xanadu tables are 8192 cells long.
            double[] f1dat = f1.Copy(); //fetch f1 the legacy way
            Assert.IsNotNull(f1dat);
            Assert.AreEqual(len, f1dat.Length);
            Assert.AreEqual(f1dat[25], f1[25]);
            double[] f1safe = f1.CopyOut(); //fetch f1 the new threadsafe way
            f1[50] = .5;
            Assert.AreEqual(.5, f1[50]);
            f1[50] = f1dat[50];//swap out a few cells via this[index]
            Assert.AreEqual(f1dat[50], f1[50]);
            Assert.AreEqual(f1dat[25], f1[25]);
            for (int i = 0; i < f1.Length; i++)
            {
                Assert.AreEqual(f1dat[i], f1safe[i]);
            }
            //try out some of the other tables, test CopyIn.
            var f2 = new Csound6Table(2, cs);

            double[] f2dat = f2.CopyOut();
            Assert.AreEqual(f1dat.Length, f2dat.Length);
            for (int i = 0; i < 2048; i++)
            {
                Assert.AreEqual((int)(f1[i + 2048] * 100000000), (int)(f2[i] * 100000000));//f1 is sine, f2 is cosine
            }
            f1.CopyIn(f2dat);
            for (int i = 0; i < f1.Length; i++)
            {
                Assert.AreEqual(f1[i], f2[i]); //did CopyIn work?
            }
            f1.CopyIn(f1dat);                  //restore
            for (int i = 0; i < f1.Length; i++)
            {
                Assert.AreEqual(f1[i], f1safe[i]);
            }
            cs.Stop(); //shut csound down. (stop not relevant in single thread but call anyway to test.
            result = cs.Cleanup();
            Assert.IsTrue(result == CsoundStatus.Success);
            cs.Dispose();
        }
コード例 #7
0
        public void TestRuntimeProperties()
        {
            bool set = Csound6Net.SetGlobalEnv("RGHMUSIC", "Henninger");

            Assert.IsTrue(set);
            object o = new Object();

            using (Csound6Net cs = new Csound6Net(o, CsoundInitFlag.NoFlags, null))
            {
                try
                {
                    m_messageText       = new StringBuilder();
                    m_count             = 0;
                    cs.MessageCallback += TestMessageEvent;

                    m_fileopened         = false;
                    cs.FileOpenCallback += TestFileOpenEvent;

                    FileInfo     csdFile   = new FileInfo("csdFiles\\Simple.csd");
                    string       path      = csdFile.FullName;
                    string       shortpath = BridgeToCpInvoke.wGetShortPathName(csdFile.FullName); //test long strings
                    CsoundStatus result    = cs.Compile(new string[] { shortpath });
                    Assert.AreEqual(CsoundStatus.Success, result);
                    object o1 = cs.HostData; //test marshalling of host data.
                    Assert.AreEqual(o, o1);
                    cs.HostData = "abc";
                    Assert.IsTrue("abc".Equals(cs.HostData));
                    string sfdir = cs.GetEnv("SFDIR");
                    Assert.IsNotNull(sfdir);
                    Assert.IsTrue(sfdir.Length > 0);
                    string garbage = cs.GetEnv("garbage");
                    Assert.IsTrue(string.IsNullOrWhiteSpace(garbage));
                    string rgh = cs.GetEnv("RGHMUSIC");
                    Assert.AreEqual("Henninger", rgh);
                    //test for sample rate, control rate, ksamps, filename from simple.csd...
                    Assert.AreEqual(44100.0, cs.Sr);
                    Assert.AreEqual(441.0, cs.Kr);
                    Assert.AreEqual(100, cs.Ksmps);
                    Assert.AreEqual(1.0, cs.OdBFS);
                    Assert.AreEqual(1, cs.Nchnls);
                    Assert.AreNotEqual(0, m_count);
                    Assert.AreEqual("simple.wav", cs.OutputFileName);

                    //confirm that all stdout text went here: for Simple.csd, chatter ends "SECTION 1:\n"
                    string text = m_messageText.ToString();
                    Assert.IsTrue(text.EndsWith("SECTION 1:\n"));
                    Assert.IsTrue(m_fileopened); //make sure we enterred the tests in TestFileOpenEvent
                }
                catch (Exception e)
                {
                    string x = e.Message;
                    Assert.Fail(x);
                }
            }
        }
コード例 #8
0
        /* Example 6 - Generating a Score
         *
         * This example continues on from Example 5, rewriting the example using
         * a Class called Note (in another class file for better reuse).
         * The note example has its ToString() method implemented
         * to generate a well-formatted Csound SCO note.
         *
         * This example also shows how a list of notes could be used multiple times.
         * The first loop through we use the notes as-is, and during the second time
         * we generate the notes again with the same properties except we alter the
         * fifth p-field up 4 semitones.
         *
         * Note: Altering a Notes values like this is alright for this example, but
         * it is a destructive edit.  Real world code might make copies of Notes or
         * alter the score generation to maintain the original values.
         */
        public void Example6()
        {
            var r = new Random();
            //Create score from a generated list of Note objects using Midi pitches 60-75.
            var notes = new List <Note>();

            for (int i = 0; i < 13; i++)       // P1  P2-start P3-Dur P4-amp   P5-frq
            {
                notes.Add(new Note(new double[] { 1, i * .25, .25, .5, r.Next(60, 75) }));
            }

            //Capture the note values as Csound parameters in a .net System.Text.StringBuilder
            var sco = new StringBuilder();

            foreach (var n in notes)
            {
                sco.AppendLine(n.ToString()); //note.ToString() will look like a score statement
            }
            //Add a major third and time displacement to the Note objects and put them in the score as well.
            foreach (var n in notes)
            {
                if (n.Pfields.Length > 4)
                {
                    n.Pfields[4] += 4;                       //pitch (p5)
                }
                if (n.Pfields.Length > 1)
                {
                    n.Pfields[1] += .125;     //start time (p2)
                }
                sco.AppendLine(n.ToString()); //More score statements with new freq and start
            }


            using (var c = new Csound6Net())
            {
                c.SetOption("-odac");   // Set option for Csound
                try
                {
                    //Now that the score has been generated, apply it to Csound:
                    c.CompileOrc(orc2);          //Compile the matching orchestra
                    c.ReadScore(sco.ToString()); //and apply the generated score

                    c.Start();
                    while (!c.PerformKsmps())
                    {
                        ;
                    }
                    c.Stop();
                }
                catch (Csound6NetException e)
                {
                    System.Console.WriteLine(string.Format("Csound failed to complete: {0}", e.Message));
                }
            }
        }
コード例 #9
0
        public async Task TestOpcodeAccess()
        {
            using (Csound6Net cs = new Csound6Net())
            {
                FileInfo     csdFile = new FileInfo("csdFiles\\Simple.csd");
                CsoundStatus result  = await cs.CompileAsync(new string[] { csdFile.FullName }); //tests raw long strings for fopen

                Assert.AreEqual(CsoundStatus.Success, result);

                IDictionary <string, IList <OpcodeArgumentTypes> > opcodes = await cs.GetOpcodeListAsync();

                Assert.IsTrue(opcodes.Count > 1000);
                Assert.IsTrue(opcodes.ContainsKey("oscil"));
                Assert.IsTrue(opcodes["oscil"].Count > 2);
                Assert.AreEqual(5, opcodes["oscil"].Count);//there should be five oscil opcode instances
                foreach (OpcodeArgumentTypes op in opcodes["oscil"])
                {
                    Assert.IsFalse(string.IsNullOrWhiteSpace(op.outypes));
                    Assert.IsFalse(string.IsNullOrWhiteSpace(op.intypes));
                    char otype = op.outypes[0];
                    Assert.IsTrue((otype == 'a') || (otype == 's'));
                    Assert.AreEqual(4, op.intypes.Length);
                    Assert.IsTrue(op.intypes.EndsWith("jo"));
                    if (otype == 's')
                    {
                        Assert.IsTrue(op.intypes.StartsWith("kk"));
                    }
                    else if (otype == 'a')
                    {
                        string start = op.intypes.Substring(0, 2);
                        Assert.IsTrue(start.Contains("a") || start.Contains("k"));
                    }
                    else
                    {
                        Assert.Fail("opcode test: output type for oscil - expected a|s got {0}", otype);
                    }
                }
                //test that modules loaded:
                Assert.IsNotNull(opcodes["pan2"]);
                Assert.AreEqual(1, opcodes["pan2"].Count);
                Assert.AreEqual("aa", opcodes["pan2"][0].outypes);
                Assert.AreEqual("axo", opcodes["pan2"][0].intypes);
                Assert.IsTrue(opcodes.Keys.Contains("granule"));

                IDictionary <string, int> namedGens = cs.GetNamedGens();
                Assert.IsTrue(namedGens.Count > 0);
                foreach (string name in namedGens.Keys)
                {
                    Assert.IsTrue(name.Length > 0);
                    Assert.IsTrue(namedGens[name] > 0);
                }
            }
        }
コード例 #10
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            using (var c = new Csound6Net())
            {
                //Using SetOption() to configure Csound: here to output in realtime

                c.CompileOrc(orc);       // Compile the Csound Orchestra string
                c.ReadScore("i1 0 1\n"); // Compile the Csound score as a string constant

                c.Start();               // When compiling from strings, Start() is needed before performing
                c.Perform();             // Run Csound to completion
                c.Stop();                // At this point, Csound is already stopped, but this call is here
            }
        }
コード例 #11
0
        /* Example 2 - Compilation with Csound without CSD
         *
         * In this example, we move from using an external CSD file to
         * embedding our Csound ORC and SCO code directly in our C# project.
         * Besides allowing encapsulation of the code within the same file,
         * using the CompileOrc() and CompileSco() API calls is useful when
         * the SCO or ORC are generated, or perhaps coming from another
         * source, such as from a database or network.
         */
        public void Example2()
        {
            using (var c = new Csound6Net())
            {
                // Using SetOption() to configure Csound: here to output in realtime
                c.SetOption("-odac");    // Note: SetOption uses only one commandline flag per call

                c.CompileOrc(orc);       // Compile the Csound Orchestra string
                c.ReadScore("i1 0 1\n");   // Compile the Csound score as a string constant

                c.Start();  // When compiling from strings, Start() is needed before performing
                c.Perform();// Run 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
        }
コード例 #12
0
        /* Example 2 - Compilation with Csound without CSD
         *
         * In this example, we move from using an external CSD file to
         * embedding our Csound ORC and SCO code directly in our C# project.
         * Besides allowing encapsulation of the code within the same file,
         * using the CompileOrc() and CompileSco() API calls is useful when
         * the SCO or ORC are generated, or perhaps coming from another
         * source, such as from a database or network.
         */
        public void Example2()
        {
            using (var c = new Csound6Net())
            {
                // Using SetOption() to configure Csound: here to output in realtime
                c.SetOption("-odac");    // Note: SetOption uses only one commandline flag per call

                c.CompileOrc(orc);       // Compile the Csound Orchestra string
                c.ReadScore("i1 0 1\n"); // Compile the Csound score as a string constant

                c.Start();               // When compiling from strings, Start() is needed before performing
                c.Perform();             // Run 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.
コード例 #13
0
        /**
         * This example does the same thing as Example4, but does it in more idiomatic C#.
         * The PerformAsync method provides for reporting progress events and responding to
         * cancellation events, but that capability is bypassed here.
         * Later examples will show how to uses these capabilities.
         */
        public async Task Example41()
        {
            using (var c = new Csound6Net())
            {
                c.SetOption("-odac");  // Set option for Csound
                c.CompileOrc(orc);     // Compile Orchestra from String
                c.ReadScore("i1 0 1"); // Read in Score from String

                c.Start();             // When compiling from strings, this call needed before performing

                //Perform the score in a background task until done
                //Neither a progress dialog or cancellation event is used in this call
                await c.PerformAsync(null, CancellationToken.None);//handles cleanup on exit
            }
        }
コード例 #14
0
   /**
    * This example does the same thing as Example4, but does it in more idiomatic C#.
    * The PerformAsync method provides for reporting progress events and responding to
    * cancellation events, but that capability is bypassed here.
    * Later examples will show how to uses these capabilities.
    */
        public async Task Example41()
        {
            using (var c = new Csound6Net())
            {
                c.SetOption("-odac");  // Set option for Csound
                c.CompileOrc(orc);     // Compile Orchestra from String
                c.ReadScore("i1 0 1");      // Read in Score from String

                c.Start();             // When compiling from strings, this call needed before performing

                //Perform the score in a background task until done
                //Neither a progress dialog or cancellation event is used in this call
                await c.PerformAsync(null, CancellationToken.None);//handles cleanup on exit
                
            }
        }
コード例 #15
0
        /* Example 5 - Generating a Score
         *
         * In this example, we will look at three techniques for generating our Score.
         * The first is one we have already seen, which is to just write out the score
         * by hand as a String.
         *
         * Knowing that we pass strings into Csound to pass note events, we can also
         * generate the string.  In the second example, sco2 starts as an empty string.
         * Using a for-loop, we append to sco2 note strings using a string formatting
         * string that has its replacement values replaced.  The replace values are
         * calculated using the i value, and the result is an ascending note line.
         *
         * In the final example, we are going to generate a list of lists.  The top-level
         * list represents our score as a whole, and each sub-list within it represents
         * the data for a single note.  The main list is then processed in two ways: first,
         * it processes each sub-list and joins the values together into a single note string;
         * second, it joins each individual note string into a single, large score string,
         * separated by newlines.  The end result is a sequence of 13 notes with random
         * pitches.
         *
         * The final example represents a common pattern of development.  For systems that
         * employ some event-based model of music, it is common to use some kind of data
         * structure to represent events.  This may use some kind of common data structure
         * like a list, or it may be represented by using a class and instances of that
         * class.
         *
         * Note, the three examples here are indicated with comments.  To listen to the examples,
         * look for the lines that have c.ReadScore(sco) (lines 80-82), uncomment the one
         * you want to hear, and comment out the others.
         */
        public void Example5(int algorithm)
        {
            //Choose one of 3 ways to create a score: sequential pitches, random pitches, or hard-coded
            var sco = new StringBuilder();
            switch (algorithm) //integer between 0 and 2
            {
                case 1:
                    for (int i = 0; i < 13; i++)
                        sco.AppendLine(string.Format("i1 {0} .25 0.5 8.{1:00}", (i * .25), i));
                    break;
                case 2:
                    var vals = new List<double[]>(); //initialize a list to hold lists of doubles
                    Random r = new Random();
                    for (int i = 0; i < 13; i++)     // populate that list
                        vals.Add(new double[] { i * .25, .25, 0.5, r.Next(15) });
                    // convert list of lists into a list of strings
                    foreach (var val in vals)
                        sco.AppendLine(string.Format("i1 {0} {1} {2} 8.{3:00}", val[0], val[1], val[2], (int)val[3]));
                    break;
                case 0:
                default:
                    sco.AppendLine("i1 0 1 0.5 8.00");  //string literal with single note
                    break;
            }

            // Once a score string has been algorithmically assembled, do the usual csound loop.
            // This time, we'll let C# Exceptions (try/catch) handle testing status for us.
            // By catching the exception, we are assured exiting the "using" block
            // and thereby disposing of csound and its memory correctly.

            using (var c = new Csound6Net())
            {
                c.SetOption("-odac");   // Set option for Csound
                try
                {
                    c.CompileOrc(orc2);         // Compile different Orchestra with moogladder
                    c.ReadScore(sco.ToString());// Read in score as built above
                    c.Start();                  // When compiling from strings, this call needed before performing
                    while (!c.PerformKsmps()) ;
                    c.Stop();
                }
                catch (Csound6NetException e)
                {
                    System.Console.WriteLine(string.Format("Csound failed to complete: {0}", e.Message));
                }
            }
        }
コード例 #16
0
        public async Task TestExternalRun()
        {
            var    fi = new FileInfo("soundFiles\\rv_mono.wav");
            string pathToSoundfile = BridgeToCpInvoke.wGetShortPathName(fi.FullName);
            var    p = new CsoundExternalProcess();

            p.ProgramName      = "sndinfo";
            p.Arguments        = new List <string>(new string[] { pathToSoundfile });
            m_count            = 0;
            m_messageText      = new StringBuilder();
            p.MessageCallback += TestMessageEvent;
            int result = await p.RunAsync(CancellationToken.None);

            Assert.AreEqual(0, result);
            Assert.IsTrue(m_count > 0);
            string text = m_messageText.ToString();

            Assert.IsTrue(text.Length > 0);
            Assert.IsTrue(text.Contains("srate 44100, monaural, 16 bit WAV"));

            using (var cs = new Csound6Net())
            {
                int count1 = m_count;
                m_count       = 0;
                m_messageText = new StringBuilder();
                long done = await cs.RunCommandAsync(new string[] { "sndinfo", pathToSoundfile }, TestMessageEvent, CancellationToken.None);

                string text2 = m_messageText.ToString();
                Assert.AreEqual(0L, done);
                Assert.AreEqual(count1, m_count);
                Assert.AreEqual(text.Substring(0, 150), text2.Substring(0, 150));//1st 150 chars should be the same - no variable statistics.

                int count2 = m_count;
                m_count       = 0;
                m_messageText = new StringBuilder();
                var sndinfo = cs.GetUtility(Csound6Utility.SHOW_SOUNDFILE_METADATA);
                sndinfo.InputFile = new FileInfo(pathToSoundfile);
                int done2 = await sndinfo.RunAsync(TestMessageEvent, CancellationToken.None);

                Assert.AreEqual(0, done2);
                Assert.IsTrue(count2 >= m_count);//sometimes 13, sometimes 14 - leading crlf
                string text3 = m_messageText.ToString();
                Assert.AreEqual(text.Substring(0, 150), text3.Substring(0, 150));
            }
        }
コード例 #17
0
        /* # Example 6 - Generating a Score
          *
         * This example continues on from Example 5, rewriting the example using
         * a Class called Note (in another class file for better reuse).
         * The note example has its ToString() method implemented
         * to generate a well-formatted Csound SCO note.
         *
         * This example also shows how a list of notes could be used multiple times.
         * The first loop through we use the notes as-is, and during the second time
         * we generate the notes again with the same properties except we alter the
         * fifth p-field up 4 semitones.
         *
         * Note: Altering a Notes values like this is alright for this example, but
         * it is a destructive edit.  Real world code might make copies of Notes or
         * alter the score generation to maintain the original values.
         */
        public void Example6()
        {
            var r = new Random();
            using (var c = new Csound6Net())
            {
                c.SetOption("-odac");   // Set option for Csound
                //Create score from a generated list of Note objects using Midi pitches 60-75.
                var notes = new List<Note>();
                for (int i = 0; i < 13; i++)
                    notes.Add(new Note(new double[] { 1, i * .25, .25, .5, r.Next(60, 75) }));

                //Capture the note values as Csound parameters in a .net System.Text.StringBuilder
                var sco = new StringBuilder();
                foreach (var n in notes)
                    sco.AppendLine(n.ToString());

                //Add a major third and time displacement to the Note objects and put them in the score as well.
                foreach (var n in notes)
                {
                    if (n.Pfields.Length > 4) n.Pfields[4] += 4; //pitch (p4)
                    if (n.Pfields.Length > 1) n.Pfields[1] += .125; //start time (p1)
                    sco.AppendLine(n.ToString());
                }

                try
                {
                    //Now that the score has been generated, apply it to Csound:
                    c.CompileOrc(orc2);         //Compile the matching orchestra
                    c.ReadScore(sco.ToString());//and apply the generated score

                    c.Start();
                    while (!c.PerformKsmps()) ;
                    c.Stop();
                }
                catch (Csound6NetException e)
                {
                    System.Console.WriteLine(string.Format("Csound failed to complete: {0}", e.Message));
                }
            }
        }
コード例 #18
0
        public async Task TestPerformAsync()
        {
            using (var cs = new Csound6Net())
            {
                var cancel = new CancellationTokenSource();
                try
                {
                    FileInfo     csf    = new FileInfo(@"csdFiles\xanadu.csd");
                    CsoundStatus result = await cs.CompileAsync(new string[] { csf.FullName });

                    cs.SetOutputFileName("f:\\PerfXanadu.wav", SoundFileType.TypWav, SampleFormat.AeShort);
                    string s = cs.OutputFileName;
                    Assert.AreEqual(CsoundStatus.Success, result);
                    cancel.CancelAfter(1500);//cancel timeout avter 1.5 seconds of computation
                    Assert.IsFalse(cancel.Token.IsCancellationRequested);
                    result = await cs.PerformAsync(null, cancel.Token);

                    Assert.Fail("Reached unexpected completion in TestPlayAsync: expected cancellation not executed."); //shouldn't execute
                }
                catch (OperationCanceledException ce)
                {//Verify that cancelation timeout occurred in a timely way.
                    var token = ce.CancellationToken;
                    Assert.AreEqual(cancel.Token, token);
                    Assert.IsTrue(token.IsCancellationRequested);
                    Assert.IsTrue(cs.ScoreTime < 50.0);
                }
                catch (Csound6NetException e)
                {
                    Assert.Fail("TestSimplePerform Error: {0}", e.Message);
                }
                catch (Exception se)
                {
                    Assert.Fail("System Exception: {0}", se.Message);
                }
                var time = cs.ScoreTime;//Confirm that cancelation worked: goes 60 sec - time at cancel...
                Assert.IsTrue(cancel.Token.IsCancellationRequested);
                Assert.IsTrue(time < 50.0);
            }
        }
コード例 #19
0
        public async Task TestAudioMidiDeviceAccess()
        {
            string midimod  = "mme";
            string audiomod = "portaudio";

            using (Csound6Net cs = new Csound6Net())
            {
                var mods = cs.GetAudioModuleList();//Csound6Net initializes to "pa"; confirm this is true.
                int cnt  = mods.Count;
                Assert.IsTrue(cnt > 0);
                Assert.IsTrue(mods.ContainsKey("pa"));
                Assert.IsFalse(mods.ContainsKey(audiomod));
                cs.SetAudioModule(audiomod); //"portaudio" won't be there yet... add it.
                mods = cs.GetAudioModuleList();
                Assert.AreEqual(cnt + 1, mods.Count);
                Assert.IsTrue(mods.ContainsKey(audiomod)); //confirm it was added

                IDictionary <string, CS_AUDIODEVICE> outputDevices = await cs.GetAudioDeviceListAsync(true);

                Assert.IsNotNull(outputDevices);
                Assert.AreNotEqual(0, outputDevices.Count);
                foreach (string id in outputDevices.Keys)
                {
                    Assert.IsNotNull(outputDevices[id]);
                    Assert.IsInstanceOfType(outputDevices[id], typeof(CS_AUDIODEVICE));
                    var dev = outputDevices[id];
                    Assert.IsTrue(dev.isOutput);
                    Assert.AreEqual(id, dev.device_id);
                    Assert.AreEqual(audiomod, dev.rt_module);
                }
                IDictionary <string, CS_AUDIODEVICE> inputDevices = await cs.GetAudioDeviceListAsync(false);

                Assert.IsNotNull(inputDevices);
                Assert.AreNotEqual(0, inputDevices.Count);
                foreach (string id in inputDevices.Keys)
                {
                    Assert.IsNotNull(inputDevices[id]);
                    Assert.IsInstanceOfType(inputDevices[id], typeof(CS_AUDIODEVICE));
                    var dev = inputDevices[id];
                    Assert.IsFalse(dev.isOutput);
                    Assert.AreEqual(id, dev.device_id);
                }

                mods = cs.GetMidiModuleList();
                Assert.IsTrue(mods.Count > 0);
                Assert.IsTrue(mods.ContainsKey("portmidi"));        //unlike for audio, csounds sets and keeps it.
                Csound6Parameters.SetOption(cs, "-+rtmidi=winmme"); //none this has an effect... stays portaudio
                cs.SetMidiModule(midimod);
                mods = cs.GetMidiModuleList();
                //count not increased - winmme and portmidi considered same? although, devices will say winmme or anything else you put there.
                bool hasMME = mods.ContainsKey(midimod);

                var midiInput = await cs.GetMidiDeviceListAsync(false);

                Assert.IsNotNull(midiInput);
                Assert.AreNotEqual(0, midiInput.Count);
                foreach (string id in midiInput.Keys)
                {
                    Assert.IsNotNull(midiInput[id]);
                    Assert.IsInstanceOfType(midiInput[id], typeof(CS_MIDIDEVICE));
                    var dev = midiInput[id];
                    Assert.IsFalse(dev.isOutput);
                    Assert.AreEqual(id, dev.device_id);
                    Assert.AreEqual(midimod, dev.midi_module);
                }

                var midiOutput = await cs.GetMidiDeviceListAsync(true);

                Assert.IsNotNull(midiOutput);
                Assert.AreNotEqual(0, midiOutput.Count);
                foreach (string id in midiOutput.Keys)
                {
                    Assert.IsNotNull(midiOutput[id]);
                    Assert.IsInstanceOfType(midiOutput[id], typeof(CS_MIDIDEVICE));
                    var dev = midiOutput[id];
                    Assert.IsTrue(dev.isOutput);
                    Assert.AreEqual(id, dev.device_id);
                }
            }
        }
コード例 #20
0
        public void TestCsound6Compiles()
        {
            string orc;
            string sco;

            string[] opts = "-R -W -d".Split(new char[] { ' ', '\t' });
            using (var orcReader = new StreamReader("classicFiles\\Simple.orc"))
            {
                orc = orcReader.ReadToEnd();
            }
            using (var scoReader = new StreamReader("classicFiles\\Simple.sco"))
            {
                sco = scoReader.ReadToEnd();
            }
            using (var cs = new Csound6Net())
            {
                var parms = new Csound6Parameters(cs);
                Assert.IsTrue(parms.IsDisplayingGraphs);
                foreach (string opt in opts)
                {
                    Assert.IsTrue(parms.SetOption(opt) == CsoundStatus.Success);                         //try with object
                }
                parms.RefreshParams();
                Assert.IsFalse(parms.IsDisplayingGraphs);
                cs.SetOutputFileName("simple1.wav", SoundFileType.TypWav, SampleFormat.AeFloat);
                Assert.AreEqual("simple1.wav", cs.OutputFileName);

                CsoundStatus result = cs.CompileOrc(orc);
                Assert.IsTrue(result == CsoundStatus.Success);

                int  kcycles  = 0;
                long lastSamp = 0;
                if (result == CsoundStatus.Success)
                {
                    result = cs.ReadScore(sco);
                    Assert.AreEqual(CsoundStatus.Success, result);
                    if (result == CsoundStatus.Success)
                    {
                        result = cs.Start();
                        while (!cs.PerformKsmps())
                        {
                            kcycles++;
                        }
                        Assert.IsTrue(kcycles > 0);
                        lastSamp = cs.CurrentTimeSamples;
                        Assert.IsTrue(lastSamp > 0L);
                        result = cs.Cleanup();
                        Assert.IsTrue(result == CsoundStatus.Success);
                    }
                }
                result = cs.Cleanup();
                Assert.AreEqual(CsoundStatus.Success, result);

                //Reset and try again with TREE-based signatures
                cs.Reset();
                //try parms via static method
                foreach (string opt in opts)
                {
                    Assert.IsTrue(Csound6Parameters.SetOption(cs, opt) == CsoundStatus.Success);
                }
                cs.SetOutputFileName("simple2.wav", SoundFileType.TypWav, SampleFormat.AeFloat);
                IntPtr tree = cs.ParseOrc(orc);
                Assert.IsNotNull(tree);
                Assert.AreNotEqual(IntPtr.Zero, tree);
                result = cs.CompileTree(tree);
                Assert.AreEqual("simple2.wav", cs.OutputFileName);
                Assert.AreEqual(CsoundStatus.Success, result);
                cs.DeleteTree(tree);
                result = cs.ReadScore(sco);
                Assert.AreEqual(CsoundStatus.Success, cs.Start());
                long crntSamp = 0L;
                while (!cs.PerformBuffer())
                {
                    Assert.IsTrue(cs.CurrentTimeSamples > crntSamp);
                    crntSamp = cs.CurrentTimeSamples;
                }
                Assert.AreEqual(lastSamp, cs.CurrentTimeSamples);//same file should yield same number of samples
                Assert.AreEqual(CsoundStatus.Success, cs.Cleanup());
            }//end using Csound6Net
        }
コード例 #21
0
        public void TestCsoundParameters()
        {
            String x = "Host Data String";

            using (Csound6Net cs = new Csound6Net(x, CsoundInitFlag.NoFlags, null))
            {
                object o = cs.HostData;
                Assert.AreEqual(x, o);
                Assert.AreEqual("Host Data String", cs.HostData);
                Csound6Parameters opts = new Csound6Parameters(cs);
                Assert.AreEqual(cs.IsDebugMode, opts.IsDebugMode);
                Assert.AreEqual(cs.MessageLevel, opts.MessageLevel);
                opts.IsDebugMode = true;
                Assert.IsTrue(opts.IsDebugMode);
                Assert.IsTrue(cs.IsDebugMode);
                opts.IsDebugMode = false;
                Assert.IsFalse(cs.IsDebugMode);
                opts.MessageLevel = MessageLevel.Amps | MessageLevel.Warnings | MessageLevel.Range;
                Assert.AreEqual(7, (int)opts.MessageLevel);
                Assert.AreEqual(7, (int)cs.MessageLevel);
                opts.HardwareBufferFrames = 2048;
                opts.SoftwareBufferFrames = 512;
                opts.ZeroDBOverride       = 1.0;
                opts.Tempo = 60;
                opts.SampleRateOverride   = 48000;
                opts.ControlRateOverride  = 48;
                opts.Heartbeat            = HeartbeatStyle.FileSize;
                opts.IsRealtimeMode       = true;
                opts.IsSampleAccurateMode = true;
                opts.IsUsingAsciiGraphs   = false;
                opts.IsUsingCsdLineCounts = false;
                opts.MaximumThreadCount   = 4;
                opts.IsSyntaxCheckOnly    = !opts.IsSyntaxCheckOnly;
                opts.IsDisplayingGraphs   = false;

                opts.MidiKey2Parameter                 = 4;
                opts.MidiKeyAsHertz2Parameter          = 5;
                opts.MidiKeyAsOctave2Parameter         = 6;
                opts.MidiKeyAsPitch2Parameter          = 7;
                opts.MidiVelocity2Parameter            = 8;
                opts.MidiVelocityAsAmplitude2Parameter = 9;
                opts.OutputChannelCountOverride        = 2;
                opts.InputChannelCountOverride         = 1;
                opts.IsAddingDefaultDirectories        = false;

                opts.IsUsingCscore       = !opts.IsUsingCscore;
                opts.WillBeepWhenDone    = !opts.WillBeepWhenDone;
                opts.IsDoneWhenMidiDone  = true;
                opts.IsDeferingGen01Load = !opts.IsDeferingGen01Load;

                //Have csound copy from oparms to CSOUND_PARAMS and confirm above values got to csound
                CSOUND_PARAMS copy = new CSOUND_PARAMS();
                opts.GetParams(copy);
                Assert.AreEqual(copy.hardware_buffer_frames, opts.HardwareBufferFrames);
                Assert.AreEqual(opts.SoftwareBufferFrames, copy.buffer_frames);
                Assert.AreEqual(opts.ZeroDBOverride, copy.e0dbfs_override);
                Assert.AreEqual(60, copy.tempo);
                Assert.AreEqual(48000.0, copy.sample_rate_override);
                Assert.AreEqual(opts.ControlRateOverride, copy.control_rate_override);
                Assert.AreEqual(3, copy.heartbeat);
                Assert.AreEqual(1, copy.realtime_mode);
                Assert.AreEqual(1, copy.sample_accurate);
                Assert.AreEqual(0, copy.ascii_graphs);
                Assert.AreEqual(0, copy.csd_line_counts);
                Assert.AreEqual(4, copy.midi_key);
                Assert.AreEqual(5, copy.midi_key_cps);
                Assert.AreEqual(6, copy.midi_key_oct);
                Assert.AreEqual(7, copy.midi_key_pch);
                Assert.AreEqual(8, copy.midi_velocity);
                Assert.AreEqual(9, copy.midi_velocity_amp);
                Assert.AreEqual(2, copy.nchnls_override);
                Assert.AreEqual(1, copy.nchnls_i_override);
                Assert.AreEqual(1, copy.no_default_paths);//double negative inverted boolean: paramater = false, no_default_paths = 1
                Assert.AreEqual(4, copy.number_of_threads);
                Assert.AreEqual(1, copy.syntax_check_only);
                Assert.AreEqual(1, copy.ring_bell);
                Assert.AreEqual(1, copy.use_cscore);
                Assert.AreEqual(0, copy.displays);
                Assert.AreEqual(1, copy.terminate_on_midi);
                Assert.AreEqual(1, copy.defer_gen01_load);
            }
        }
コード例 #22
0
        public void TestMiscellaneousObjects()
        {
            var rnd31 = new Csound6Rand31();

            Assert.IsInstanceOfType(rnd31, typeof(Csound6Rand31));
            ISet <int> vals = new HashSet <int>();

            for (int i = 0; i < 100; i++)
            {
                int val = rnd31.next();
                Assert.IsFalse(vals.Contains(val));
                vals.Add(val);
            }
            var rndMT = new Csound6RandMT();

            Assert.IsInstanceOfType(rndMT, typeof(Csound6RandMT));
            ISet <uint> uvals = new HashSet <uint>();

            for (int i = 0; i < 100; i++)
            {
                uint uval = (uint)rndMT.Next();
                Assert.IsFalse(uvals.Contains(uval));
                uvals.Add(uval);
            }

            var timer = new Csound6Timer();

            Thread.Sleep(100);
            double cpu   = timer.CPUTime;
            double realt = timer.RealTime;

            Thread.Sleep(100);
            Assert.IsTrue(timer.CPUTime > cpu);
            double newreal = timer.RealTime;

            //    Assert.IsTrue(timer.RealTime > realt); //realtime isn't working in csound?

            using (var cs = new Csound6Net())
            {
                var gv1 = new Csound6GlobalVariable <int>("MyInt", cs);
                Assert.AreEqual(4, gv1.Size);
                gv1.Value = 255;
                int x = gv1.Value;
                Assert.AreEqual(255, x);
                var gv2 = new Csound6GlobalVariable <double>("MyDouble", cs);
                gv2.Value = 3.14;
                float y = (float)gv2.Value;
                Assert.AreEqual(3.14f, y);

                //Test strings, structs and classes
                var gv3 = new Csound6GlobalStringVariable("MyString", cs);
                gv3.Value = "";
                Assert.AreEqual(string.Empty, gv3.Value);

                string testString = "This is Richard's String";
                gv3.Value = testString;
                string s = gv3.Value;
                Assert.AreEqual(testString, s);

                var gv4 = new Csound6GlobalVariable <CSOUND_PARAMS>("MyParms", cs);
                gv4.Value = cs.GetParameters().GetParams(new CSOUND_PARAMS());
                Assert.AreEqual(135, (int)gv4.Value.message_level);
                var parms = gv4.Value;
                parms.hardware_buffer_frames = 2048;
                Assert.AreNotEqual(gv4.Value.hardware_buffer_frames, parms.hardware_buffer_frames);
                gv4.Value = parms;
                Assert.AreEqual(2048, gv4.Value.hardware_buffer_frames);
                Assert.AreEqual(135, (int)gv4.Value.message_level);
                Assert.AreEqual(1, gv4.Value.csd_line_counts);
            }

            using (var cs = new Csound6Net())
            {
                var utilities = cs.GetUtilities();
                Assert.IsTrue(utilities.Count > 0);
                foreach (string name in utilities.Keys)
                {
                    Assert.IsFalse(string.IsNullOrWhiteSpace(name));
                    var utility = utilities[name];
                    Assert.IsInstanceOfType(utility, typeof(Csound6Utility), string.Format("Utility <{0}> is not valid type, is type={1}", name, utility));
                    string desc = utility.Description;
                    Assert.IsFalse(string.IsNullOrWhiteSpace(desc));
                }
            }
        }