You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将音频生成函数输出的多个列表合并为一个列表?

Combine Multiple Note Sample Lists into One Single List

Hey there! I see you're building an audio editor and want to merge those separate sample lists from each note into one unified list. Let's adjust your code to make that happen—here's how:

Step 1: Modify note_to_list to return the vector instead of printing it

Right now, your function just prints each note's sample list and discards it. Instead, we'll have it return the generated vector so we can collect and merge them later. We'll also add a fix for the 'Q' note to avoid division by zero errors:

import math

def note_to_frequency(note):
    if note == 'A': return 440
    if note == 'B': return 494
    if note == 'C': return 523
    if note == 'D': return 587
    if note == 'E': return 659
    if note == 'F': return 698
    if note == 'G': return 784
    if note == 'Q': return 0

def note_to_list(input_note, input_time_play):
    vector = []
    time_play = int(input_time_play)
    frequency = note_to_frequency(input_note)
    sample_rate = 2000
    lenght_vector = int(sample_rate * time_play / 16)
    
    # Handle silent note 'Q' to prevent division by zero
    if frequency == 0:
        # Fill with silent samples (0,0) for the full duration
        vector = [[0, 0] for _ in range(lenght_vector)]
        return vector
    
    sample_per_cycle = sample_rate / frequency
    for i in range(lenght_vector):
        a = int(32767 * math.sin(math.pi * 2 * i / sample_per_cycle))
        vector.append([a, a])
    
    return vector  # Return the sample list instead of printing it

Step 2: Collect and merge all note vectors into one list

Create a master list (combined_vector) and use the extend() method to add each note's samples to it. Unlike append(), extend() adds individual elements from the note's vector instead of nesting the whole list:

input_data = ['F', '1', 'G', '1']
combined_vector = []  # This will hold all merged samples

if len(input_data) % 2 == 0:
    for i in range(0, len(input_data), 2):
        # Get the sample list for the current note
        note_samples = note_to_list(input_data[i], input_data[i + 1])
        # Merge it into the combined list
        combined_vector.extend(note_samples)

# Now print the single combined list
print(combined_vector)

What this does:

  • The combined_vector will now contain all the sample pairs from your 'F' note followed by all samples from your 'G' note (or any other notes in your input_data), in one flat list.
  • We added a safety check for the 'Q' silent note to avoid crashing when frequency is 0—this was a hidden bug in your original code!

内容的提问来源于stack exchange,提问作者MV912HB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:35:47