for part_index, part in enumerate(score.parts):
measure_number = 1
for measure in part.getElementsByClass(stream.Measure):
time_signature = measure.timeSignature
key_signature = measure.keySignature
metronome_mark = measure.metronomeMarkBoundaries()[0][2] if measure.metronomeMarkBoundaries() else None
for element in measure.notesAndRests:
dynamics = None # Инициализация переменной
element_info = {
'part_index': part_index + 1,
'type': '',
'pitch': '',
'duration': element.duration.quarterLength,
'offset': element.offset,
'measure': measure_number,
'time_signature': str(time_signature) if time_signature else None,
'key_signature': str(key_signature) if key_signature else None,
'dynamics': None,
'articulations': None,
'harmony': None
}
if not element.isRest:
if hasattr(element, 'volume') and element.volume.velocityScalar is not None:
dynamics = element.volume.velocityScalar
element_info['dynamics'] = dynamics
if isinstance(element, note.Note):
element_info['type'] = 'note'
element_info['pitch'] = str(element.pitch)
elif isinstance(element, chord.Chord):
element_info['type'] = 'chord'
element_info['pitch'] = '+'.join(str(p) for p in element.pitches)
element_info['harmony'] = extract_harmony(element)
elements.append(element_info)
if dynamics is not None:
emotion = analyze_emotion(str(key_signature), dynamics, metronome_mark)
possible_scenes = emotion_to_scene.get(emotion, [])
scene_description = random.choice(possible_scenes) if possible_scenes else 'неопределенная сцена'
scenes.append((measure_number, emotion, scene_description))
emotion_counts[emotion] += 1
measure_number += 1
return elements, scenes, emotion_counts
def visualize_emotions(emotion_counts):
plt.bar(emotion_counts.keys(), emotion_counts.values())
plt.xlabel('Emotion')
plt.ylabel('Count')
plt.title('Emotion Distribution in Composition')
plt.show()
Пример использования функции
elements, scenes, emotion_counts = extract_notes_and_chords('C:/Users/ARTYOM/Documents/Python/Bring_it_up.musicxml')
for e in elements:
print(e)
for measure_number, emotion, scene_description in scenes:
print(f"Такт: {measure_number}, Эмоция: {emotion}, Предлагаемая сцена: {scene_description}")
visualize_emotions(emotion_counts)
To ensure that everything works correctly, let's break down the process of extracting and analyzing musical elements from a MusicXML file into key functions, and visualize the results.
Key Function Breakdown:
Analyze Emotion: This function extends the analysis of emotions by incorporating tempo. Specific tempos are considered to help determine whether the music is 'joyful', 'peaceful', 'tense', or 'sad'.
Extract Harmony: This function analyzes a chord element to determine its harmonic function (e.g., Major Triad, Dominant Seventh).
Extract Notes and Chords: This core function parses the MusicXML file, extracts key musical elements (notes, chords, rests), and collects data on their dynamic markings, pitch, duration, and harmony. It also uses the logic from analyze_emotion to classify each measure and suggest scenes.
Visualize Emotions: This function provides a graphical representation of the emotional content extracted from the composition, allowing you to visually analyze the emotional distribution.
Implementing and Running Functions:
Ensure that all necessary libraries and files are in place. The full script provided should be executed in an environment where the music21 library and matplotlib are both installed. Additionally, make sure that the file path to the MusicXML file is correct.
Here is the full integrated code for extracting notes and chords from a MusicXML file, analyzing emotions, and visualizing the results:
python
from music21 import converter, note, chord, stream, tempo
import random
import matplotlib.pyplot as plt
# Placeholder dictionary for emotion to scene mapping
emotion_to_scene = {
'joyful': ["A sunny day in the park.", "A cheerful gathering of friends."],
'tense': ["A suspenseful chase scene.", "A high-stakes negotiation."],
'sad': ["A rainy day with a somber mood.", "A moment of reflection."],
'peaceful': ["A serene landscape.", "A quiet evening at home."]
}
def analyze_emotion(key_signature, dynamics, metronome_mark):
if 'minor' in key_signature:
emotion = 'sad'
elif dynamics > 0.7:
emotion = 'joyful'
else:
emotion = 'peaceful'
if metronome_mark:
if metronome_mark.number > 120:
emotion = 'joyful' if emotion == 'peaceful' else 'tense'
return emotion
def extract_harmony(chord_element):
root = chord_element.root()
if chord_element.isDominantSeventh():
return f"Dominant Seventh ({root})"
elif chord_element.isDiminishedSeventh():
return f"Diminished Seventh ({root})"
elif chord_element.isMajorTriad():
return f"Major Triad ({root})"
elif chord_element.isMinorTriad():
return f"Minor Triad ({root})"
else:
return f"Chord ({root})"
def extract_notes_and_chords(file_path):
score = converter.parse(file_path)
elements = []
scenes = []
emotion_counts = {'joyful': 0, 'tense': 0, 'sad': 0, 'peaceful': 0}
for part_index, part in enumerate(score.parts):
measure_number = 1
for measure in part.getElementsByClass(stream.Measure):
time_signature = measure.timeSignature
key_signature = measure.keySignature
metronome_mark = measure.metronomeMarkBoundaries()[0][2] if measure.metronomeMarkBoundaries() else None
for element in measure.notesAndRests:
dynamics = None # Initialize variable for dynamics
element_info = {
'part_index': part_index + 1,
'type': '',
'pitch': '',
'duration': element.duration.quarterLength,
'offset': element.offset,
'measure': measure_number,
'time_signature': str(time_signature) if time_signature else None,
'key_signature': str(key_signature) if key_signature else None,
'dynamics': None,
'articulations': None,
'harmony': None
}
if not element.isRest:
if hasattr(element, 'volume') and element.volume.velocityScalar is not None:
dynamics = element.volume.velocityScalar
element_info['dynamics'] = dynamics
if isinstance(element, note.Note):
element_info['type'] = 'note'
element_info['pitch'] = str(element.pitch)
elif isinstance(element, chord.Chord):
element_info['type'] = 'chord'
element_info['pitch'] = '+'.join(str(p) for p in element.pitches)
element_info['harmony'] = extract_harmony(element)
elements.append(element_info)
if dynamics is not None:
emotion = analyze_emotion(str(key_signature), dynamics, metronome_mark)
possible_scenes = emotion_to_scene.get(emotion, [])
scene_description = random.choice(possible_scenes) if possible_scenes else 'неопределенная сцена'
scenes.append((measure_number, emotion, scene_description))
emotion_counts[emotion] += 1
measure_number += 1
return elements, scenes, emotion_counts
def visualize_emotions(emotion_counts):
plt.bar(emotion_counts.keys(), emotion_counts.values())
plt.xlabel('Emotion')
plt.ylabel('Count')
plt.title('Emotion Distribution in Composition')
plt.show()
# Example usage
elements, scenes, emotion_counts = extract_notes_and_chords('path/to/your/MusicXMLfile.musicxml')
for e in elements:
print(e)
for measure_number, emotion, scene_description in scenes:
print(f"Measure: {measure_number}, Emotion: {emotion}, Suggested Scene: {scene_description}")
visualize_emotions(emotion_counts)
Note:
Replace 'path/to/your/MusicXMLfile.musicxml' with the actual path to your MusicXML file.
This script uses a placeholder emotion_to_scene dictionary. Adjust this dictionary to suit the specific scenes you want based on emotions.
Ensure all supporting libraries (music21, matplotlib) are installed in your Python environment. You can install them using pip:
sh
pip install music21 matplotlib
Running the Script:
Prepare the MusicXML file at the correct path.
Run the script in your Python environment.
Inspect the printed output of musical elements and scenes.
Visualize the emotion distribution with the bar chart generated by matplotlib.
This workflow should provide a thorough analysis of the musical composition with visual insight into its emotional landscape.