Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # random_music_generator.py
- import struct
- import wave
- import os
- import math
- import random
- # Constants for the audio settings
- BITRATE = 90 # in bps
- CHANNELS = 2 # stereo
- FRAMERATE = 44100 # in "Hz" :
- SAMPLESIZE = 2 # in bytes
- MAX_VOLUME = 32767 # max value for 16-bit audio
- DURATION = 240 # in seconds (4 minutes)
- PADDING = 8 # number of digits for padding in file names
- # Save the audio data to an MP3 file
- def save_as_mp3():
- for i, track in enumerate(audio_data):
- # Generate a file name with padding
- file_name = 'track_{:0{padding}}.mp3'.format(i, padding=PADDING)
- # Create a new wave file
- wave_file = wave.open(file_name, 'w')
- # Set the audio settings for the wave file
- wave_file.setnchannels(CHANNELS)
- wave_file.setsampwidth(SAMPLESIZE)
- wave_file.setframerate(FRAMERATE)
- wave_file.setcomptype('MP3', 'MP3')
- wave_file.setparams((CHANNELS, SAMPLESIZE, FRAMERATE, 0, 'NONE', 'not compressed'))
- # Write the audio data to the wave file
- wave_file.writeframes(track)
- # Close the wave file
- wave_file.close()
- def generate_music_track():
- # Generate the left and right channels for the music track
- left_channel = []
- right_channel = []
- for i in range(DURATION * FRAMERATE):
- # Generate a random volume for the left channel
- left_volume = random.randint(0, MAX_VOLUME)
- # Generate a random frequency for the left channel
- left_frequency = random.uniform(200, 400)
- # Generate a sine wave for the left channel
- left_sample = int(left_volume * math.sin(2 * math.pi * i * left_frequency / FRAMERATE))
- # Generate a random volume for the right channel
- right_volume = random.randint(0, MAX_VOLUME)
- # Generate a random frequency for the right channel
- right_frequency = random.uniform(200, 400)
- # Generate a sine wave for the right channel
- right_sample = int(right_volume * math.sin(2 * math.pi * i * right_frequency / FRAMERATE))
- # Add the samples to the left and right channels
- left_channel.append(struct.pack('h', left_sample))
- right_channel.append(struct.pack('h', right_sample))
- # Combine the left and right channels into a single audio track
- audio_track = b''.join([left + right for left, right in zip(left_channel, right_channel)])
- return audio_track
- drum_beat = []
- def generate_drum_beat():
- del drum_beat[:]
- for i in range(DURATION * FRAMERATE):
- # Generate a random volume for the drum beat
- volume = random.randint(0, MAX_VOLUME)
- # Generate a random frequency for the drum beat
- frequency = random.uniform(200, 400)
- # Generate a sine wave for the drum beat
- sample = int(volume * math.sin(2 * math.pi * i * frequency / FRAMERATE))
- # Add the sample to the drum beat
- drum_beat.append(struct.pack('h', sample))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement