### Install Sphinx with pip Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/buildingDocumentation.rst Install the Sphinx documentation generator. Use 'sudo pip3 install sphinx' on Mac and 'pip3 install sphinx' on Windows. ```bash sudo pip3 install sphinx ``` ```bash pip3 install sphinx ``` -------------------------------- ### Import music21 in Python Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installMac.rst After starting the Python interpreter, type this to verify that music21 has been installed correctly. This should not produce any errors. ```python import music21 ``` -------------------------------- ### Install Jupyter and IPython Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/installJupyter.ipynb Install the necessary Jupyter and IPython packages using pip. Ensure you have a working pip installation of music21 first. ```bash sudo pip install jupyter $ sudo pip install ipython ``` -------------------------------- ### Display Key Signature Example (13a) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Displays a standard key signature example. This is useful for visualizing common key signatures. ```python s('13a') ``` -------------------------------- ### Get Verticality at Offset (Start Example) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_61_trees.ipynb Demonstrates creating a Verticality object at offset 0, which can include non-pitched elements like text boxes and metadata. ```python v_start = tsTree.getVerticalityAt(0) ``` ```python v_start ``` -------------------------------- ### Install Sphinx for Documentation Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/documenting.rst Install Sphinx, a documentation generator, using pip3. This is necessary for building documentation from .rst files. ```bash pip3 install sphinx ``` -------------------------------- ### Installing Dependencies with uv sync Source: https://github.com/cuthbertlab/music21/blob/master/AGENTS.md Command to install runtime dependencies and the development group, which includes optional extras like scipy and python-Levenshtein, essential for tests. ```bash uv sync ``` -------------------------------- ### Create and Show Example Score Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_timespans.ipynb Generates an example score using music21's tree module and displays it visually. ```python score = tree.makeExampleScore() score.show() ``` -------------------------------- ### Install music21 using pip Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installWindows.rst Use this command to download and install the music21 library. This is the standard method for installing Python packages. ```bash pip install music21 ``` -------------------------------- ### Parse and Display Bach Example Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_08_installingMusicXML.ipynb Loads a Bach piece from the music21 corpus, selects the first six measures, and displays it. Ensure music21 is installed with its corpus module. ```python b = corpus.parse('bach/bwv66.6') b = b.measures(0, 5) #_DOCS_HIDE b.show() # I've altered this so it's much shorter than it should be... ``` -------------------------------- ### Cross-Staff Beaming (Failing Example) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb This example is intended to demonstrate cross-staff beaming but is noted as failing in music21. ```python s('43d') # failing # cross-staff-beaming. fails utterly in m21 so far. ``` -------------------------------- ### Install anywidget Package Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_widgets.ipynb Installs the 'anywidget' package using pip. This is a prerequisite for creating custom Jupyter widgets, as it's not part of the standard music21 ecosystem. ```python %pip install anywidget ``` -------------------------------- ### Run Jupyter Notebook Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/documenting.rst Navigate to the desired directory and run this command to start a Jupyter Notebook server. ```bash jupyter notebook ``` -------------------------------- ### Install Jupyter Notebook Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/documenting.rst Install Jupyter Notebook using pip3. This is required for editing .ipynb documentation files. ```bash pip3 install jupyter ``` -------------------------------- ### Configure music21 Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installLinux.rst Run this command to configure music21 after installation. You will be prompted to provide the path to your MusicXML reader. ```bash python3 -m music21.configure ``` -------------------------------- ### Setting Explicit Start and Stop Ties Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_31_clefs.ipynb Illustrates the importance of explicitly setting both 'start' and 'stop' ties when required by analysis programs, although music21 often infers the stop tie from the start tie. ```python c1 = chord.Chord('C#4 E4 G4') c2 = chord.Chord('C4 E4 G4') c1[1].tie = tie.Tie('start') c2[1].tie = tie.Tie('stop') c1[2].tie = tie.Tie('start') c2[2].tie = tie.Tie('stop') s = stream.Stream() s.append([c1, c2]) s.show() ``` -------------------------------- ### Display Three-Note Chords with Durations Example (21c) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Presents three-note chords with varying durations. This example is useful for testing how different note lengths within chords are handled. ```python s('21c') ``` -------------------------------- ### Display Basic Chord Example (21a) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Shows a simple chord consisting of two notes. This is a fundamental example for chord representation. ```python s('21a') ``` -------------------------------- ### Install nbconvert with pip Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/buildingDocumentation.rst Use this command to install the nbconvert package, which is needed for converting Jupyter notebooks to documentation format. Omit 'sudo' on Windows. ```bash sudo pip3 install nbconvert ``` -------------------------------- ### Install PyAudio on Mac Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installAdditional.rst Use these commands to install PyAudio on a Mac. PyAudio allows for recording within Python and is used for the audioSearch module. It requires portaudio and Xcode command-line development tools. ```bash xcode-select --install brew install portaudio pip3 install pyaudio ``` -------------------------------- ### Display Key Signature Cancellation Example (13ab) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Tests key signature cancellation. Note: This example is not supported by MuseScore. ```python s('13ab') # no music21 support; blocked MuseScore ``` -------------------------------- ### Module-Level Documentation String Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/documenting.rst Example of a module-level documentation string. This should be placed at the top of a Python module before import statements. ```python ''' I am documentation for this module! ''' ``` -------------------------------- ### Install or Upgrade music21 Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installLinux.rst Use pip to download and install or upgrade to the latest version of music21. This command should be run in your terminal. ```bash pip3 install --upgrade music21 ``` -------------------------------- ### Create Notes with Start, Continue, and Stop Ties Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_31_clefs.ipynb Manually creates three C4 notes with 'start', 'continue', and 'stop' tie types, appends them to a measure, and displays the result. This demonstrates the 'continue' tie type. ```python c0 = note.Note('C4') c0.tie = tie.Tie('start') c1 = note.Note('C4') c1.tie = tie.Tie('continue') c2 = note.Note('C4') c2.tie = tie.Tie('stop') s = stream.Measure() s.append([c0, c1, c2]) s.show() ``` -------------------------------- ### Simple Piano Staff Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb A basic example of creating a piano staff in MusicXML using music21. ```python s('43a') ``` -------------------------------- ### Run the music21 documentation build script Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/buildingDocumentation.rst Navigate to the documentation directory within the music21 installation and run this script to build the documentation. It will automatically open your web browser. ```bash python3 make.py ``` -------------------------------- ### Recursive Harmonic Analysis Example Source: https://github.com/cuthbertlab/music21/blob/master/music21/romanText/clercqTemperley_format.html Demonstrates a recursive notation for harmonic analysis, where sections are defined by symbols that can be reused in higher-level expressions. The example shows a song structure with verses, choruses, and a key. ```text VP: I IV | Vr: $VP $VP I ii | V | Ch: I V | vi IV | S: [C] $Vr $Ch $Vr $Ch $Ch I | ``` -------------------------------- ### Get Start Timespans at Time 22.0 Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_timespans.ipynb Retrieves and displays timespans that start at offset 22.0 for the verticality at 22.0. ```python v22.startTimespans ``` -------------------------------- ### Tied Notes in MusicXML Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Illustrates two simple tied whole notes. This example focuses on the basic implementation of ties. ```python s('33b') # not necessarily a spanner except in Lilypond ``` -------------------------------- ### Generate Notehead Styles in Chords (MuseScore) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Use the s('22c') command to generate examples of different notehead styles within chords. This tests the element for individual notes in a chord. Note that this specific example is blocked by MuseScore. ```python s('22c') # blocked by MuseScore: 22a ``` -------------------------------- ### Configure music21 from IDLE Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installWindows.rst Import music21 in IDLE and then call the run() function to initiate the configuration process for helper programs. ```python import music21 music21.configure.run() ``` -------------------------------- ### Get Start Timespans at Time 3.5 Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_timespans.ipynb Retrieves and displays timespans that start at offset 3.5 for the specified verticality. ```python v35.startTimespans ``` -------------------------------- ### Initialize Analysis Tool and Results Storage Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_unconvertedExamples.ipynb Sets up an analysis tool for melodic interval diversity and prepares a list to store the results of corpus searches. ```python # Get an analysis tool diversityTool = analysis.discrete.MelodicIntervalDiversity() # get a list to store results. results = [] ``` -------------------------------- ### Get Elements Starting at Offset Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_61_trees.ipynb Retrieve all timespans that begin at a specific offset in the timespan tree. This is useful for finding all musical events that start at a precise moment. ```python tsTree.elementsStartingAt(7.0) ``` -------------------------------- ### Initialize note articulations list Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_32_articulations.ipynb Demonstrates how to check the articulations list of a note, which is initially empty. ```Python n1 = note.Note('A4') n1.articulations ``` -------------------------------- ### Get a Measure Stack Across All Parts Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_06_stream2.ipynb The `.measures(start, end)` method can be called on a whole score to get a 'measureStack', which is a collection of measures across all parts for the specified measure numbers. ```python measureStack = sBach.measures(2, 3) measureStack.show() ``` -------------------------------- ### Get the Tie Type as a String Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_31_clefs.ipynb Retrieves the type of the tie ('start' or 'stop') as a string from the `.type` attribute of a Tie object. ```python n1.tie.type ``` ```python n1.next('Note').tie.type ``` -------------------------------- ### Display Extreme Key Signature Example (13aa) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Displays extreme key signature examples, including those with many flats or sharps. Note: MuseScore and Finale may have issues with flats. ```python s('13aa') # blocked: MuseScore and Finale (on flats; sharps import fine) ``` -------------------------------- ### Install SciPy on Mac (python.org) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installAdditional.rst Use this command to install SciPy if you are using the Python version from python.org on a Mac. SciPy provides scientific extensions to Python and is used for accelerating audio searching and fast-Fourier transforms. ```bash pip3 install scipy ``` -------------------------------- ### Get Generic Interval Size Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_20_examples2.ipynb Retrieves the generic size of an interval, ignoring its direction. For example, both a major second and a minor second have a generic interval of 2. ```python firstInterval.generic ``` -------------------------------- ### Create UserSettings Configuration File Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_24_environment.ipynb Import environment and create a UserSettings object, then call create() to generate an XML environment file. This file stores persistent settings. ```python from music21 import * us = environment.UserSettings() #_DOCS_SHOW us.create() ``` -------------------------------- ### Create and Append a Start Beam Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_31_clefs.ipynb Manually creates a Beam object with the type 'start' and number '1', then appends it to the Beams object of a note. This is useful for explicitly defining the beginning of a beam group. ```python beam1 = beam.Beam(type='start', number=1) ``` ```python d1Beams = d1.beams d1Beams.append(beam1) d1.beams ``` -------------------------------- ### Get spanners attached to an element Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_29_spanners.ipynb Query an element to see all spanners it belongs to using `.getSpannerSites()`. An element can be part of multiple spanners, as demonstrated by the example output. ```python g.getSpannerSites() ``` -------------------------------- ### Playing a Note via MIDI Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_02_notes.ipynb Use the .show('midi') method to play a Note object as MIDI. This requires specific OS and QuickTime versions on some platforms. ```python f.show('midi') ``` -------------------------------- ### Generic Class Example Source: https://github.com/cuthbertlab/music21/blob/master/CLAUDE.md Illustrates the bracket syntax for generic classes in Python 3.12+. ```python class Stream[M21ObjType: base.Music21Object]: ``` -------------------------------- ### Initialize TinyNotation Converter Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_16_tinyNotation.ipynb Instantiate the TinyNotation Converter with a music string to parse. ```python tnc = tinyNotation.Converter('6/8 e4. d8 c# d e2.') ``` -------------------------------- ### Get Verticality at Offset Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_61_trees.ipynb Create a Verticality object representing the musical state at a specific offset. This object aggregates elements that start, overlap, or stop at that exact moment. ```python v = tsTree.getVerticalityAt(8.0) ``` ```python v ``` -------------------------------- ### Fetch Latest Commits Source: https://github.com/cuthbertlab/music21/blob/master/CLAUDE.md Command to run at the start of every session to ensure work begins from the latest commits. ```bash git fetch ``` -------------------------------- ### Get a Range of Measures from a Part Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_06_stream2.ipynb Use the `.measures(start, end)` method on a part to extract a Stream containing measures within the specified range. The part is accessed by its index. ```python alto = sBach.parts[1] # parts count from zero, so soprano is 0 and alto is 1 excerpt = alto.measures(1, 4) excerpt.show() ``` -------------------------------- ### Class Inheritance Example Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_06_stream2.ipynb Demonstrates basic class inheritance in Python, showing how a subclass can access attributes from its parent class. ```python class Japan: food = 'sushi' drink = 'sake' class Okinawa(Japan): evenBetterFood = 'spam potstickers' ``` -------------------------------- ### Generate Transposing Instruments Example Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Generates a MusicXML file demonstrating transposing instruments like Trumpet in Bb and Horn in Eb. Shows how different instruments display the same scale. ```python s('72a') ``` -------------------------------- ### Get All Time Points Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_61_trees.ipynb Retrieve a sorted tuple of all unique time points where any element in the timespan tree either starts or stops. This provides a comprehensive overview of all significant temporal events. ```python tsTree.allTimePoints()[:13] ``` -------------------------------- ### Get music21 source file path Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/buildingDocumentation.rst If you cannot locate your music21 installation, use these Python commands to import music21 and find the source file path. The documentation directory is typically located above this path. ```python from music21 import * common.getSourceFilePath() ``` -------------------------------- ### Get MeterSequence Level Span Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_55_advancedMeter.ipynb The `getLevelSpan` method returns the time span of each node at a given depth as a list of start and end values. This helps in understanding the temporal extent of meter components at a specific level. ```python ms.getLevelSpan(1) ``` ```python ms[1].getLevelSpan(1) ``` -------------------------------- ### Configure music21 from Command Prompt Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installWindows.rst Execute this command in the command prompt to configure music21 and set up paths for helper programs like MuseScore or Finale. ```bash python3 -m music21.configure ``` -------------------------------- ### Get the first and last elements of a spanner Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_29_spanners.ipynb Retrieve the first and last elements contained within a spanner using the `.getFirst()` and `.getLast()` methods. This helps in identifying the start and end points of a spanned musical phrase. ```python sl2.getFirst() ``` ```python sl2.getLast() ``` -------------------------------- ### Display Mid-Measure Key Change Example (13e) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Demonstrates key changes occurring within a measure, showing transitions between different key signatures. ```python s('13e') ``` -------------------------------- ### Refined Regular Expression Search Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_11_corpusSearching.ipynb Employ a more specific regular expression to match terms at the beginning of a word, improving search accuracy. This example refines the previous search to only match names starting with 'ha' followed by any character and then 'd'. ```python import re haydnOrHandel = re.compile(r'^ha.d.*', re.IGNORECASE) ``` -------------------------------- ### Search Metadata Using a Compiled Regular Expression Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_11_corpusSearching.ipynb Use compiled regular expressions to search metadata fields. This example demonstrates searching for names starting with 'ha' followed by any character and then 'd', case-insensitively. Be aware that broad patterns may yield unexpected results. ```python import re haydnOrHandel = re.compile(r'ha.d.*', re.IGNORECASE) corpus.corpora.CoreCorpus().search(haydnOrHandel) ``` -------------------------------- ### Run Configuration Tool Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_08_installingMusicXML.ipynb Executes the music21 configuration tool to detect and set up external music notation software like MuseScore, Finale, or Sibelius. Respond 'no' to prompts unless you need to specify a custom path. ```python #_DOCS_SHOW configure.run() ``` -------------------------------- ### Instantiating and Running a Plot Class Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_44_advancedGraphing.ipynb Demonstrates how to create an instance of a specific plot class (ScatterPitchClassOffset) and then execute its run() method to generate the plot. ```python scatter = graph.plot.ScatterPitchClassOffset(bach) scatter ``` ```python scatter.run() ``` -------------------------------- ### Displaying a Note as MusicXML Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_02_notes.ipynb Use the .show() method to display a Note object. By default, it renders as a MusicXML image if a reader is installed. ```python f.show() ``` -------------------------------- ### Access Start Timespans Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_timespans.ipynb Retrieves and displays the timespans that start at the beginning of the selected verticality. ```python v4.startTimespans ``` -------------------------------- ### Convert Example Score to Timespans Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_timespans.ipynb Converts the generated example score into a Timespan collection for analysis. ```python tsColSmall = score.asTimespans() ``` -------------------------------- ### Run Test Case '01a' Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Executes the test case '01a' which focuses on pitches and accidentals. This involves parsing a MusicXML file and displaying the result, likely for visual verification. ```python s('01a') ``` -------------------------------- ### Install music21 on macOS Sierra or El Capitan Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installMac.rst Use this command in the Terminal to install music21. You will be prompted for your password. ```bash sudo pip3 install music21 ``` -------------------------------- ### Display Chord Visualization Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_07_chords.ipynb Use the `.show()` method to display a visual representation of the chord. This requires additional setup and may not work in all environments. ```python cMinor.show() ``` ```python cMajor.show() ``` -------------------------------- ### Generate Full Transposing Instruments Example Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Generates a MusicXML file with various transpositions, showing different display pitches for the same concert pitch. Includes untransposed instruments. ```python s('72b') ``` -------------------------------- ### Access Element from Start Timespan Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_timespans.ipynb Extracts a specific start timespan and its associated musical element from the verticality at 3.5. ```python elTsC = v35.startTimespans[0] print(elTsC, elTsC.element) ``` -------------------------------- ### Run Documentation Tests Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/testing.ipynb Execute this command in the documentation directory to test documentation changes. Ensure you are using Python 3. ```bash testDocumentation.py ``` -------------------------------- ### Handle Too Many Parts Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb This example addresses a scenario where a MusicXML file contains more part elements than are listed in the part-list. The library can either convert all available parts or ignore the unlisted ones. The snippet is noted as producing warnings. ```python s('41h') # warns, skips the part -- acceptable behavior ``` -------------------------------- ### Create and Display a Note Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/about/what.ipynb Create a musical note with a specific pitch and duration, then display it visually. This demonstrates basic note object creation and manipulation. ```python n = note.Note('D#3') n.duration.type = 'half' n.show() ``` -------------------------------- ### Display Church Modes Key Signature Example (13b) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Displays key signatures for all church modes (major, minor, ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian) with two sharps. ```python s('13b') ``` -------------------------------- ### Setting Key and Transposing Notes Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_15_key.ipynb Creates a stream with D major and B-flat minor keys, appends F-natural whole notes, and then transposes the notes up a half step to observe spelling changes. ```python s = stream.Stream() s.append(key.Key('D')) s.append(note.Note('F', type='whole')) s.append(key.Key('b-', 'minor')) s.append(note.Note('F', type='whole')) s2 = s.makeNotation() s2.show() ``` ```python for n in s2.recurse().notes: n.transpose(1, inPlace=True) s2.show() ``` -------------------------------- ### Get Roman Numeral Figure and Key Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_23_romanNumerals.ipynb Accesses the `figureAndKey` property of a RomanNumeral object to get a combined string representation of the numeral and its key. ```python rf.figureAndKey ``` -------------------------------- ### Show MIDI Output Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/notebook_show_tests.ipynb Displays a piece in MIDI format using the .show('midi') method. This is useful for interactive playback or embedding MIDI within a notebook. ```python c.show('midi') ``` -------------------------------- ### Load music21 and IPython Extension Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/testsAndInProgress/devTest_unconvertedExamples.ipynb Initial setup for using music21 within an IPython environment. This code is typically run once at the beginning of a session. ```python # ignore this %load_ext music21.ipython21 from music21 import * ``` -------------------------------- ### Import Chords as Grace Notes Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Imports MusicXML where chords are represented as grace notes. ```python s('24b') ``` -------------------------------- ### Add Music Files to New Metadata Bundle Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_53_advancedCorpus.ipynb Creates a new metadata bundle and adds music files from specified paths. Returns a list of paths that failed to be added. ```python newBundle = metadata.bundles.MetadataBundle() paths = corpus.corpora.CoreCorpus().search('corelli') failedPaths = newBundle.addFromPaths(paths) failedPaths ``` -------------------------------- ### Inspect Start and End Notes of an Interval Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_20_examples2.ipynb Retrieves the starting and ending 'Note' objects of a specific 'Interval' object. This helps in understanding the melodic context of the interval. ```python firstInterval = allIntervals[0] firstInterval.noteStart ``` ```python firstInterval.noteEnd ``` -------------------------------- ### Get Memory Address of an Object Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_12_music21object.ipynb Uses the built-in Python `id()` function to get the memory address of a music21 object, which is the default value for the `.id` attribute. ```python id(n) ``` -------------------------------- ### Show Stream (Implicitly Makes Ties) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_31_clefs.ipynb Displays a stream. The `show()` method implicitly calls `makeTies` to ensure the music can be displayed correctly in MusicXML, even if ties were previously stripped. ```python littleStripped.show() ``` -------------------------------- ### Get Elements by Offset in Music21 Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Use getElementsByOffset() to retrieve elements at a specific offset or within a range. Add .stream() to get a Stream object from the result. ```python sOut = stream1.getElementsByOffset(3) len(sOut) ``` ```python sOut[0] ``` ```python sOut = stream1.getElementsByOffset(2, 3).stream() sOut.show('text') ``` -------------------------------- ### Import Tremolo Tuplets Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Imports tremolo tuplets from MusicXML. Ensure the application supports tuplet duration scaling. ```python s('23e') ``` -------------------------------- ### Enable music21 Notebook Extension Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/installJupyter.ipynb Enable the 'usability/sphinx-markdown/main' notebook extension. This command initiates the enabling process and may show validation issues. ```python E = notebook.nbextensions.EnableNBExtensionApp() E.toggle_nbextension('usability/sphinx-markdown/main') ``` -------------------------------- ### Install Matplotlib on Mac (python.org) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installAdditional.rst Use this command to install Matplotlib if you are using the Python version from python.org on a Mac. Matplotlib is used for graphing and visual displays in music21. ```bash pip3 install matplotlib ``` -------------------------------- ### Verticality Start Timespans (Non-Pitched) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_61_trees.ipynb Display the start timespans for a Verticality at offset 0, which may include non-pitched elements such as text boxes, metadata, and layout information. ```python v_start.startTimespans[:10] ``` -------------------------------- ### Create specific articulation objects Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_32_articulations.ipynb Shows how to create instances of specific articulation classes like Staccato and Accent. ```Python stac = articulations.Staccato() acc = articulations.Accent() ``` -------------------------------- ### Install Pygame on Mac Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installAdditional.rst Use this command to install Pygame on a Mac. Pygame allows for real-time MIDI performance and is used in the midi.realtime module. Pygame 1.9 or later is required. ```bash pip3 install pygame ``` -------------------------------- ### Create a basic Articulation object Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_32_articulations.ipynb Demonstrates how to create a generic Articulation object. This is the base class for all articulations. ```Python from music21 import * art = articulations.Articulation() art ``` -------------------------------- ### Get Offset by Site in Music21 Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Use getOffsetBySite() for a more robust way to get an element's offset within a specific Stream, especially when an element might be in multiple Streams. ```python note2.offset ``` ```python note2.getOffsetBySite(stream1) ``` -------------------------------- ### Create and Configure a New Local Corpus in Python Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_53_advancedCorpus.ipynb Creates a new named local corpus, assigns a directory for music files, and saves its settings. This allows for persistent, custom corpus management across sessions. ```python from music21 import * aNewLocalCorpus = corpus.corpora.LocalCorpus('newCorpus') aNewLocalCorpus.existsInSettings ``` ```python aNewLocalCorpus.addPath('~/Desktop') #_DOCS_SHOW aNewLocalCorpus.directoryPaths print("('/Users/j_wolf/Desktop',)") #_DOCS_HIDE ``` ```python aNewLocalCorpus.save() aNewLocalCorpus.existsInSettings ``` -------------------------------- ### Install NumPy on Mac (python.org) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installAdditional.rst Use this command to install NumPy if you are using the Python 3 version from python.org on a Mac. NumPy provides numeric extensions to Python and is included with Matplotlib. ```bash pip3 install numpy ``` -------------------------------- ### List Available UserSettings Keys Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_24_environment.ipynb Iterate through the keys of a UserSettings object to see all configurable environment settings. This helps in understanding what can be customized. ```python for key in sorted(us.keys()): print(key) ``` -------------------------------- ### Display Chord Example in Context (21d) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Shows chords appearing in the second measure, following ornaments and dynamics in the first measure. This tests chord detection in a more complex musical context. ```python s('21d') # Chords in the second measure, after several ornaments in the first measure and a p at the beginning of the second measure. ``` -------------------------------- ### Install Matplotlib on Mac (Anaconda) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/installing/installAdditional.rst Use these commands to install Matplotlib if you are using a version of Python from Anaconda (conda, miniconda, etc.) on a Mac. Matplotlib is used for graphing and visual displays in music21. ```bash conda install matplotlib conda install python.app ``` -------------------------------- ### Creating a Note Object Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_02_notes.ipynb Demonstrates the correct way to create a Note object using the music21 library. Avoid using 'note' as a variable name to prevent conflicts with the 'note' module. ```python note = note.Note("C#3") ``` -------------------------------- ### Generate MusicXML for Voice 2 Starting Later Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Generates a MusicXML file where the second voice is intended to start on the second beat of the first full measure. This tests synchronization of multiple voices. ```python s('46e') ``` -------------------------------- ### Configure StrongAccent direction and placement Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_32_articulations.ipynb Demonstrates setting the pointDirection and placement for a StrongAccent articulation. ```Python sacc = articulations.StrongAccent() sacc.pointDirection sacc.placement = 'above' ``` -------------------------------- ### Create and Populate a Stream Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Create a new Stream, add a Note to it at offset 0, and then append another Stream to it. ```python biggerStream = stream.Stream() note2 = note.Note('D#5') biggerStream.insert(0, note2) biggerStream.append(stream1) ``` -------------------------------- ### Invalid Variable Name Example Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_02_notes.ipynb This example demonstrates an invalid attempt to name a variable 'b-flat' using a hyphen. Python syntax does not allow hyphens in variable names, leading to a SyntaxError. Use underscores or camelCase instead. ```python b-flat = note.Note("B-2") ``` -------------------------------- ### Chord List Output Example Source: https://github.com/cuthbertlab/music21/blob/master/music21/romanText/clercqTemperley_format.html Presents the 'chord list' format for harmonic analysis, showing chords on a timeline defined by measures. This format is generated by the expander program and includes timing information. ```text 0.00 0.50 I 0 1 0 0 0.50 1.00 IV 5 4 0 5 1.00 1.50 I 0 1 0 0 1.50 2.00 IV 5 4 0 5 (etc.) ``` -------------------------------- ### Get altered pitches Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_15_key.ipynb Retrieve a list of pitches that are altered by the key signature. ```python ks2.alteredPitches ``` -------------------------------- ### Get Undirected Interval Value Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_20_examples2.ipynb Retrieves the undirected generic value of an interval. ```python secondInterval.generic.undirected ``` -------------------------------- ### Create and append Notes, Rests, and Chords to a Stream Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_07_chords.ipynb Demonstrates creating a Rest and a Note, setting their durations, and appending them along with a pre-defined Chord to a Stream. Use this to build simple musical sequences. ```python rest1 = note.Rest() rest1.quarterLength = 0.5 noteASharp = note.Note('A#5') noteASharp.quarterLength = 1.5 stream2 = stream.Stream() stream2.append(cMinor) stream2.append(rest1) stream2.append(noteASharp) stream2.show() ``` -------------------------------- ### Running the music21 Test Suite Source: https://github.com/cuthbertlab/music21/blob/master/AGENTS.md Provides commands to run the music21 test suite using either a multiprocessing approach or a single-core approach, depending on the machine's capabilities. ```bash music21/test/multiprocessTest.py ``` ```bash testSingleCoreAll.py ``` -------------------------------- ### Get Directed Interval Value Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_20_examples2.ipynb Retrieves the directed generic value of an interval. ```python secondInterval = allIntervals[1] secondInterval.generic.directed ``` -------------------------------- ### Display Key Signature Octaves Example (13ac) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Tests key signatures at different octaves, including cancellation. Note: MuseScore and Finale do not support octave information for key signatures. ```python s('13ac') # no music21 support; blocked MuseScore + Finale ``` -------------------------------- ### Get Stream Representation Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Display the string representation of a music21 Stream object. ```python stream1 ``` -------------------------------- ### Run Test Case '01d' Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Executes the test case '01d' which covers microtones. It parses and displays MusicXML files containing various microtonal accidentals. ```python s('01d') ``` -------------------------------- ### Get Note Representation Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Display the string representation of a music21 Note object. ```python note1 ``` -------------------------------- ### Get List Length Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Returns the number of elements currently in a Python list. ```python len(noteList) ``` -------------------------------- ### Multi-Staff with Different Keys and Clefs at Start Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/musicxmlTest.ipynb Demonstrates a piano staff where each staff has different keys and clefs, all defined at the beginning of the measure. ```python s('43b') ``` -------------------------------- ### Run All Music21 Tests (Single Core) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/testing.ipynb Execute all tests for the music21 library on a single core. This method is used for modules that do not work well with multiprocessing or are in obscure subdirectories, and should be run before major releases. ```bash python3 test/singleCoreAll.py ``` -------------------------------- ### Get scale from KeySignature Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_15_key.ipynb Retrieve the Major or Minor scale corresponding to a given KeySignature. ```python ks2.getScale('major') ``` ```python ks2.getScale('minor') ``` -------------------------------- ### Get Roman Numeral Key Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_23_romanNumerals.ipynb Retrieves the `Key` object associated with each RomanNumeral object. ```python (rf.key, rc.key, rb.key) ``` -------------------------------- ### Get ID of a Part Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_12_music21object.ipynb Retrieves the ID of a music21 Part object, which in this case is 'Soprano'. ```python sopr.id ``` -------------------------------- ### Access Stream Duration Type Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Get the type of the Duration object for a music21 Stream. ```python stream1.duration.type ``` -------------------------------- ### Typical Music21 Usage with Stream Manipulation Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_58_sitesContext.ipynb Illustrates a common music21 pattern involving stream creation, insertion, and retrieval of notes. This example highlights how new streams are created and how the first note can change after modifications. ```python p = stream.Part() m = stream.Measure() p.insert(0, m) m.insert(1, note.Note('D')) firstNote = p.recurse().notes.first() m.insert(0, note.Note('C')) newFirstNote = p.recurse().notes.first() (firstNote, newFirstNote) ``` -------------------------------- ### Get Note Duration Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_04_stream1.ipynb Retrieves the duration of a music21 Note object in quarter lengths. ```python note2.duration.quarterLength ``` -------------------------------- ### Create KeySignature object Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_15_key.ipynb Create a KeySignature object by specifying the number of sharps. Positive integers indicate sharps, while negative integers indicate flats. ```python ks2 = key.KeySignature(2) ks2.sharps ``` ```python ks7 = key.KeySignature(7) ks7 ``` -------------------------------- ### Example Usage of getLastChord (Python) Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_20_examples2.ipynb Demonstrates calling the getLastChord function with a BWV 10 score. ```python getLastChord(bwv10) ``` -------------------------------- ### Creating a Duration Object Directly Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_19_duration2.ipynb Shows how to instantiate a music21 Duration object with a specified quarter length. ```python d = duration.Duration(4.0) d ``` -------------------------------- ### Sphinx Italics Text Example Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/developerReference/documenting.rst To italicize text in reStructuredText, enclose the text in single asterisks. ```rst *This is italics* ``` -------------------------------- ### Get Tonal Certainty of a Key Analysis Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_15_key.ipynb Calculates the tonal certainty of a key analysis result. ```python fis.tonalCertainty() ``` -------------------------------- ### Create and Print Time Signature Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_14_timeSignatures.ipynb Demonstrates creating a TimeSignature object and printing its numerator and denominator. Requires importing the music21 library. ```python from music21 import * noteC = note.Note('C4', type='half') noteD = note.Note('D4', type='quarter') noteE = note.Note('E4', type='quarter') noteF = note.Note('F4', type='half') tsThreeFour = meter.TimeSignature('3/4') print(tsThreeFour.numerator, '/', tsThreeFour.denominator) ``` -------------------------------- ### Getting Score Length Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_06_stream2.ipynb Retrieves the number of top-level elements within a music21 Score object. ```python len(sBach) ``` -------------------------------- ### Get Treble Clef Sign Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_31_clefs.ipynb Retrieves the sign for a TrebleClef, which is 'G' for the standard treble clef. ```python treble = clef.TrebleClef() treble.sign ``` -------------------------------- ### Write and Read Custom Format File Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_54_extendingConverter.ipynb Write data to a temporary file with the '.sb' extension and then parse it using converter.parse(), demonstrating file handling. ```python from music21 import environment e = environment.Environment() f = e.getTempFile('.sb') with open(fp, 'w') as f: f.write('CDC DE F GAGB GE C DEFED C') print(fp) ``` -------------------------------- ### Create a chord from pitch classes and display it Source: https://github.com/cuthbertlab/music21/blob/master/documentation/source/usersGuide/usersGuide_07_chords.ipynb Constructs a chord using a list of pitch classes and displays its musical notation. Pitch classes are integers from 0 to 11. ```python oddChord = chord.Chord([1, 3, 7, 9, 10]) oddChord.show() ```