Advertisement
Jann24

music_composition_template.py

Dec 3rd, 2024
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.28 KB | None | 0 0
  1. import numpy as np
  2. from scipy.io import wavfile
  3.  
  4. class MusicGenerator:
  5.  
  6.     def __init__(self, sampling_rate):
  7.         self.sampling_rate = sampling_rate
  8.  
  9.     def generate_sine_wave(self, frequency, duration, amplitude):
  10.         """
  11.        Generates a simple audio signal with a sine wave form.
  12.  
  13.        Arguments:
  14.            frequency: The frequency of the signal in Hz.
  15.            duration: The duration of the signal in seconds.
  16.            amplitude: The amplitude of the signal.
  17.  
  18.        Returns:
  19.            A simple audio signal with a sine wave form.
  20.        """
  21.  
  22.         # Calculate number of samples
  23.         num_samples = int(self.sampling_rate*duration)
  24.  
  25.         # Generate a time scale.
  26.         time = np.linspace(0, duration, num_samples, endpoint=False)
  27.  
  28.         # Form the audio signal.
  29.         audio_signal = amplitude * np.sin(2 * np.pi * frequency * time)
  30.  
  31.         return audio_signal
  32.  
  33.     def generate_music(self, notes):
  34.         """
  35.        Generates a simple musical composition.
  36.  
  37.        Arguments:
  38.            notes: A list of notes to play.
  39.  
  40.        Returns:
  41.            composed music.
  42.        """
  43.  
  44.         # Generate the audio signals for each note.
  45.         composed_music = np.array([])
  46.         for note in notes:
  47.             note_length = note[2]
  48.             audio_signal = self.generate_sine_wave(note[1], note_length, 0.2)
  49.             composed_music = np.append(composed_music, audio_signal)
  50.  
  51.         return composed_music
  52.  
  53.     def save_signal_to_wav(self, filename, signal):
  54.         """
  55.        Save a signal to a WAV file.
  56.  
  57.        Arguments:
  58.            filename (str): The name of the output WAV file.
  59.            signal (numpy.ndarray): The signal data as a NumPy array.
  60.  
  61.        Returns:
  62.            None
  63.        """
  64.         # Calculate the maximum amplitude of the signal
  65.         max_amplitude = np.max(np.abs(signal))
  66.        
  67.         # Normalize the signal to the range [-1, 1]
  68.         if max_amplitude > 0:
  69.             normalized_signal = signal / max_amplitude
  70.         else:
  71.             normalized_signal = signal
  72.  
  73.         # Convert to 16-bit PCM format
  74.         int_signal = np.int16(normalized_signal * 32767)
  75.        
  76.         # Write the signal to a WAV file
  77.         wavfile.write(filename, self.sampling_rate, int_signal)
  78.        
  79.  
  80. def main():
  81.  
  82.     sampling_rate = 44100
  83.    
  84.     # Create a music generator with the given sampling rate
  85.     music_generator = MusicGenerator(sampling_rate)
  86.  
  87.     # Define musical notes with frequency and duration for "Für Elise" in a higher octave
  88.     notes = [
  89.         ('E5', 659.26, 0.5),   # E in the 5th octave
  90.         ('D#5', 622.25, 0.5),  # D# in the 5th octave
  91.         ('E5', 659.26, 0.5),   # E in the 5th octave
  92.         ('D#5', 622.25, 0.5),  # D# in the 5th octave
  93.         ('E5', 659.26, 0.5),   # E in the 5th octave
  94.         ('B4', 493.88, 0.5),   # B in the 4th octave
  95.         ('D5', 587.33, 0.5),   # D in the 5th octave
  96.         ('C5', 523.25, 0.5),   # C in the 5th octave
  97.         ('A4', 440.00, 1),   # A in the 4th octave
  98.     ]
  99.  
  100.     # Generate the music.
  101.     composed_music = music_generator.generate_music(notes)
  102.  
  103.     # Save the music.
  104.     music_generator.save_signal_to_wav("composed_music.wav", composed_music)
  105.  
  106. if __name__ == "__main__":
  107.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement