Python Script Melody

Here’s a simple Python script using the `pygame` library to play a melody. You can install the library with `pip install pygame` if you don't already have it.

This script will play a sequence of notes for a melody.

```python
import pygame
import time

# Initialize pygame mixer
pygame.mixer.init()

# Define a dictionary for notes and their corresponding frequencies
notes = {
    'C4': 261.63,
    'D4': 293.66,
    'E4': 329.63,
    'F4': 349.23,
    'G4': 392.00,
    'A4': 440.00,
    'B4': 493.88,
    'C5': 523.25
}

# Define the melody sequence with (note, duration) tuples
melody = [
    ('C4', 0.5), ('D4', 0.5), ('E4', 0.5), ('F4', 0.5),
    ('G4', 0.5), ('A4', 0.5), ('B4', 0.5), ('C5', 0.5)
]

# Function to play a note
def play_note(frequency, duration):
    sound = pygame.sndarray.make_sound(pygame.sndarray.array([4096 * pygame.mixer.Sound(pygame.mixer.Sound.get_length(pygame.mixer.Sound(frequency)))]))
    sound.play(-1)
    time.sleep(duration)
    sound.stop()

# Play the melody
for note, duration in melody:
    play_note(notes[note], duration)

# Clean up pygame mixer
pygame.mixer.quit()
```

### How it works:

1. **Initialization:** The script starts by initializing `pygame.mixer`.
2. **Notes Dictionary:** It defines a dictionary mapping note names to their corresponding frequencies.
3. **Melody Sequence:** The `melody` list contains tuples, where each tuple represents a note and its duration.
4. **play_note Function:** This function plays a sound at the given frequency for a specified duration.
5. **Loop Through Melody:** The script loops through each note in the melody, playing it for the appropriate duration.

### Note:
- `pygame.sndarray.make_sound()` might not work directly with frequencies like this. In a real-world scenario, you might need to load actual sound files for each note, or use a different library such as `pydub` or `simpleaudio` for generating tones programmatically.

You might also want to adjust the code based on your specific needs and the library's capabilities.

Comments

Popular posts from this blog

Set Up Dos Games on websites or App

Data Types - SQL

Smart Monitor