ffmpeg下载

链接:https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z

生成10秒曲子代码 好难听

from pydub import AudioSegment
import numpy as np

# Helper function to create a 10-second melody segment
def create_melody_segment(sample_rate=22050, style='guofeng', duration=10):
    # Initialize the audio stream
    audio = np.zeros((duration * sample_rate, 2), dtype=np.float32)

    # Define scale: Pentatonic for Guofeng, Chromatic for Hip-hop
    scale = [0, 2, 4, 7, 9] if style == 'guofeng' else list(range(12))

    # Set tempo (beats per minute)
    bpm = 120 if style == 'guofeng' else 90

    # Calculate beat duration
    beat_duration = sample_rate * 60 // bpm

    # Function to add a note
    def add_note(note, start, end, volume=1.0):
        frequency = 440 * (2 ** (note / 12))
        t = np.linspace(0, end - start, int((end - start) * sample_rate), False)
        note_audio = np.sin(2 * np.pi * frequency * t) * volume

        note_audio_length = len(note_audio)
        audio_length = end - start
        if note_audio_length < audio_length:
            note_audio = np.pad(note_audio, (0, audio_length - note_audio_length), 'constant')
        elif note_audio_length > audio_length:
            note_audio = note_audio[:audio_length]

        audio[start:end, :] += note_audio[:, np.newaxis]

    # Create the melody segment
    current_position = 0
    while current_position + beat_duration < len(audio):
        if np.random.rand() > 0.3:  # Add a note 70% of the time
            note = np.random.choice(scale) + 12 * np.random.randint(1, 3)  # Choose octave
            start = current_position
            end = start + beat_duration
            add_note(note, start, end, volume=0.5)
        current_position += beat_duration

    return audio

# Generate a 10-second melody segment
style = 'guofeng'
melody_segment = create_melody_segment(style=style)

# Convert the numpy array to audio segment
audio_segment = AudioSegment(
    melody_segment.tobytes(),
    frame_rate=22050,
    sample_width=melody_segment.dtype.itemsize,
    channels=2
)

# Save the audio segment to a file
output_file_segment = 'guofeng_melody_10s.mp3'
audio_segment.export(output_file_segment, format="mp3")

print(output_file_segment)


参考:https://blog.csdn.net/m0_46278037/article/details/113790540

posted @ 2023-12-30 20:21  __username  阅读(12)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。