[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KHW8JRTJFKR5D3W16Q7R3M":3,"skill-same:01M6KHW8JRTJFKR5D3W16Q7R3M":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":25,"publishedAt":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":13,"repositoryHtmlUrl":44,"repositoryHomepageUrl":6,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M6KHW8JRTJFKR5D3W16Q7R3M","aligned-stem-workflow",null,"Incremental audio production with duration alignment handling, per-stem verification, and adaptive extension strategies","AG064\u002FOpenSpace","AG064","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184930299?v=4","01M6KHVFG7TB73NHX3RDYSTMH2","01M6KHVFMM7XA2PZA9Z83PHS3V",0,"MIT","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced\u002FSKILL.md",[17,22],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发",[26,27,28,29,30,31,32,33,34,35],"workflow","aligned stem workflow","verification","Production","Audio","alignment","strategies","extension","with","adaptive","2026-11-10 10:12:30",false,"---\nname: aligned-stem-workflow\ndescription: Incremental audio production with duration alignment handling, per-stem verification, and adaptive extension strategies\n---\n\n# Aligned Stem Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **incremental verification**, **fail-fast** principles, and **automatic duration alignment**. Each major step produces verified outputs before proceeding, with explicit handling for stem duration mismatches using appropriate extension strategies.\n\n## Overview\n\nFollow these steps in strict order. Each step must complete successfully and pass verification before proceeding to the next:\n\n1. **Early timing calculation** - Derive section transitions from BPM and duration first\n2. **Verify reference audio** - Validate input file properties and extract target duration\n3. **Generate and verify each stem individually** - One stem at a time with immediate verification\n4. **Detect and resolve duration mismatches** - Apply appropriate extension strategy (zero-pad, loop, or crossfade)\n5. **Generate drum stem separately** - Dedicated drum extension with rhythm patterns\n6. **Apply effects with verification** - Process each stem and verify output\n7. **Export master track** - Mix all verified stems\n8. **Archive and final verification** - Package deliverables with comprehensive checks\n\n## Key Differences from Standard Workflow\n\n- **Incremental verification**: Verify each stem immediately after generation, not just at the end\n- **Fail-fast approach**: Stop and report errors at each step rather than accumulating failures\n- **Early timing**: Calculate section transitions before any audio generation\n- **Duration alignment**: Explicit detection and resolution of stem duration mismatches\n- **Adaptive extension**: Choose appropriate strategy (zero-pad\u002Floop\u002Fcrossfade) based on stem type\n- **Separated drums**: Drum stem generation is a distinct step with rhythm-specific processing\n- **Memory-efficient**: Process stems individually to avoid large array operations that cause sandbox failures\n\n## Step 1: Calculate Timing Parameters (Early)\n\nCalculate all timing parameters **before** generating any audio. This ensures consistent timing across all stems:\n\n```python\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    \"\"\"Calculate beat-aligned transition points for song sections.\"\"\"\n    beats_per_second = bpm \u002F 60.0\n    \n    section_durations = {}\n    cumulative_time = 0\n    \n    for section_name, beat_count in sections.items():\n        duration = beat_count \u002F beats_per_second\n        section_durations[section_name] = {\n            'start': cumulative_time,\n            'end': cumulative_time + duration,\n            'beats': beat_count,\n            'start_beat': cumulative_time * beats_per_second\n        }\n        cumulative_time += duration\n    \n    return section_durations\n\n# Configuration\nBPM = 120\nDURATION = 137\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ntiming = calculate_section_transitions(BPM, DURATION, SECTIONS)\nprint(\"Timing calculated:\")\nfor section, data in timing.items():\n    print(f\"  {section}: {data['start']:.2f}s - {data['end']:.2f}s ({data['beats']} beats)\")\n```\n\n## Step 2: Verify Reference Audio\n\nValidate the reference file exists and has expected properties:\n\n```python\nimport soundfile as sf\nimport os\n\ndef verify_reference_file(filepath, expected_sample_rate=None, min_duration=None):\n    \"\"\"Verify reference audio file and return info dict.\"\"\"\n    if not os.path.exists(filepath):\n        raise FileNotFoundError(f\"Reference file not found: {filepath}\")\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        errors.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f\"Duration too short: expected >= {min_duration}s, got {info.duration}s\")\n    \n    if errors:\n        raise ValueError(f\"Reference file validation failed: {'; '.join(errors)}\")\n    \n    print(f\"Reference verified: {info.duration:.2f}s @ {info.samplerate}Hz, {info.channels}ch, {info.subtype}\")\n    return {\n        'sample_rate': info.samplerate,\n        'duration': info.duration,\n        'channels': info.channels,\n        'subtype': info.subtype\n    }\n\n# Verify reference\nref_info = verify_reference_file('reference.wav', expected_sample_rate=48000, min_duration=130)\nTARGET_DURATION = ref_info['duration']  # Use actual reference duration as target\n```\n\n## Step 3: Generate and Verify Each Stem Individually\n\nGenerate one stem at a time, verify it immediately before proceeding to the next:\n\n```python\nimport numpy as np\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT', section_timing=None):\n    \"\"\"Generate a single stem with explicit sample type.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    \n    # Generate stem-specific content (customize per stem type)\n    if name == 'bass':\n        freq = 110  # A2\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.8\n    elif name == 'guitars':\n        freq = 440  # A4\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.6\n    elif name == 'synths':\n        freq = 880  # A5\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.5\n    elif name == 'bridge':\n        freq = 220  # A3\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.7\n    else:\n        audio_data = np.sin(2 * np.pi * 440 * t) * 0.5\n    \n    # Ensure proper data type\n    if subtype == 'FLOAT':\n        audio_data = audio_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        audio_data = np.clip(audio_data, -1, 1) * (2**23 - 1)\n        audio_data = audio_data.astype(np.int32)\n    \n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\ndef verify_stem(filepath, expected_sample_rate, expected_subtype, expected_duration, tolerance_sec=1.0):\n    \"\"\"Verify a single stem meets specifications.\"\"\"\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if info.subtype != expected_subtype:\n        errors.append(f'subtype: expected {expected_subtype}, got {info.subtype}')\n    \n    if abs(info.duration - expected_duration) > tolerance_sec:\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    # Calculate duration discrepancy\n    duration_diff = info.duration - expected_duration\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors), 'duration_diff': duration_diff}\n    \n    return {'success': True, 'info': info, 'duration_diff': duration_diff}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\nstem_info = {}  # Track duration discrepancies\n\nfor stem_name in STEM_NAMES:\n    print(f\"\\n=== Generating {stem_name} stem ===\")\n    \n    # Generate\n    filepath, data = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype=SUBTYPE)\n    \n    # Verify immediately\n    result = verify_stem(filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} stem verified: {result['info'].duration:.2f}s @ {result['info'].samplerate}Hz\")\n        if abs(result['duration_diff']) > 0.1:\n            print(f\"  ⚠ Duration discrepancy: {result['duration_diff']:+.2f}s\")\n        generated_stems.append(filepath)\n        stem_info[stem_name] = result\n    else:\n        print(f\"✗ {stem_name} stem FAILED: {result['error']}\")\n        raise RuntimeError(f\"Stem generation failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(generated_stems)} stems generated and verified successfully\")\n```\n\n## Step 4: Detect and Resolve Duration Mismatches\n\nWhen stems have different durations, apply the appropriate extension strategy:\n\n### Strategy Selection Guidelines\n\n| Strategy | Best For | Duration Gap | Sound Characteristic |\n|----------|----------|--------------|---------------------|\n| **Zero-padding** | Short gaps (\u003C0.5s), silence sections, endings | Small | Clean, abrupt |\n| **Looping** | Repetitive patterns (drums, bass, rhythmic elements) | Medium to large | Seamless, rhythmic |\n| **Crossfade extension** | Melodic content, sustained instruments, vocals | Any | Natural, smooth |\n\n```python\ndef align_stem_duration(input_filepath, output_filepath, target_duration, strategy='auto', \n                        sample_rate=None, subtype='FLOAT', loop_seamless=True):\n    \"\"\"\n    Align stem duration to target using appropriate strategy.\n    \n    Args:\n        input_filepath: Path to source stem\n        output_filepath: Path for aligned output\n        target_duration: Target duration in seconds\n        strategy: 'zero_pad', 'loop', 'crossfade', or 'auto'\n        sample_rate: Sample rate (auto-detected if None)\n        subtype: Audio subtype\n        loop_seamless: Apply crossfade at loop boundaries if True\n    \n    Returns:\n        dict with success status and alignment details\n    \"\"\"\n    if not os.path.exists(input_filepath):\n        return {'success': False, 'error': f'Input file not found: {input_filepath}'}\n    \n    # Load source\n    data, sr = sf.read(input_filepath)\n    if sample_rate is None:\n        sample_rate = sr\n    \n    source_duration = len(data) \u002F sample_rate\n    duration_diff = target_duration - source_duration\n    \n    # If already aligned (within tolerance), just copy\n    if abs(duration_diff) \u003C 0.01:\n        sf.write(output_filepath, data, sample_rate, subtype=subtype, format='WAV')\n        return {'success': True, 'strategy': 'none', 'duration_diff': 0}\n    \n    if duration_diff > 0:\n        # Need to EXTEND\n        extend_frames = int(duration_diff * sample_rate)\n        \n        if strategy == 'auto':\n            # Auto-select based on duration gap and stem type\n            if duration_diff \u003C 0.5:\n                strategy = 'zero_pad'\n            elif 'drum' in input_filepath or 'bass' in input_filepath:\n                strategy = 'loop'\n            else:\n                strategy = 'crossfade'\n        \n        if strategy == 'zero_pad':\n            # Append zeros\n            padding = np.zeros(extend_frames, dtype=data.dtype)\n            aligned_data = np.concatenate([data, padding])\n            \n        elif strategy == 'loop':\n            # Loop the content\n            loop_frames = len(data)\n            loops_needed = int(np.ceil(extend_frames \u002F loop_frames))\n            \n            if loop_seamless and loops_needed > 1:\n                # Apply crossfade at loop boundaries for seamless looping\n                crossfade_frames = min(int(0.05 * sample_rate), loop_frames \u002F\u002F 4)\n                loop_extension = np.zeros(extend_frames, dtype=data.dtype)\n                \n                for i in range(loops_needed):\n                    start = i * loop_frames\n                    end = min(start + loop_frames, extend_frames)\n                    actual_len = end - start\n                    \n                    # Extract loop segment\n                    loop_segment = data[:actual_len].copy()\n                    \n                    # Apply crossfade at boundaries\n                    if i > 0 and actual_len >= crossfade_frames * 2:\n                        # Fade in from previous loop\n                        fade_in = np.linspace(0, 1, crossfade_frames)\n                        loop_segment[:crossfade_frames] *= fade_in\n                    \n                    if i \u003C loops_needed - 1 and actual_len >= crossfade_frames * 2:\n                        # Fade out for next loop\n                        fade_out = np.linspace(1, 0, crossfade_frames)\n                        loop_segment[-crossfade_frames:] *= fade_out\n                    \n                    loop_extension[start:end] = loop_segment\n                \n                extend_frames_actual = len(loop_extension)\n            else:\n                # Simple tiling\n                loop_extension = np.tile(data, loops_needed)[:extend_frames]\n                extend_frames_actual = extend_frames\n            \n            aligned_data = np.concatenate([data, loop_extension[:extend_frames_actual]])\n            \n        elif strategy == 'crossfade':\n            # Extend using crossfade from the end of the source\n            # Take last portion and crossfade it onto itself\n            fade_duration = min(duration_diff * 0.3, 2.0)  # 30% of gap, max 2s\n            fade_frames = int(fade_duration * sample_rate)\n            \n            if fade_frames >= len(data) \u002F\u002F 2:\n                # Source too short for crossfade, fall back to loop\n                fade_frames = len(data) \u002F\u002F 4\n            \n            # Extract tail segment for extension\n            tail_segment = data[-fade_frames:].copy()\n            \n            # Create extended portion with crossfade\n            extended_portion = np.zeros(extend_frames, dtype=data.dtype)\n            \n            if extend_frames \u003C= fade_frames:\n                # Short extension: just crossfade tail onto itself\n                fade_in = np.linspace(0, 1, extend_frames)\n                extended_portion = tail_segment[:extend_frames] * fade_in\n            else:\n                # Longer extension: loop tail with crossfades\n                loops = int(np.ceil(extend_frames \u002F fade_frames))\n                for i in range(loops):\n                    start = i * fade_frames\n                    end = min(start + fade_frames, extend_frames)\n                    seg_len = end - start\n                    \n                    segment = tail_segment[:seg_len].copy()\n                    \n                    # Crossfade boundaries\n                    if seg_len >= 100:\n                        cf_len = min(50, seg_len \u002F\u002F 4)\n                        if i > 0:\n                            fade_in = np.linspace(0, 1, cf_len)\n                            segment[:cf_len] *= fade_in\n                    \n                    extended_portion[start:end] = segment\n            \n            aligned_data = np.concatenate([data, extended_portion])\n        \n        else:\n            return {'success': False, 'error': f'Unknown extension strategy: {strategy}'}\n        \n    else:\n        # Need to TRUNCATE\n        truncate_frames = int(abs(duration_diff) * sample_rate)\n        aligned_data = data[:len(data) - truncate_frames]\n        strategy = 'truncate'\n    \n    # Ensure proper data type and clip\n    if subtype == 'FLOAT':\n        aligned_data = aligned_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        aligned_data = np.clip(aligned_data, -1, 1) * (2**23 - 1)\n        aligned_data = aligned_data.astype(np.int32)\n    else:\n        aligned_data = np.clip(aligned_data, -1, 1)\n    \n    # Export aligned stem\n    sf.write(output_filepath, aligned_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return {\n        'success': True, \n        'strategy': strategy,\n        'source_duration': source_duration,\n        'target_duration': target_duration,\n        'duration_diff': duration_diff,\n        'aligned_frames': len(aligned_data)\n    }\n\n# Apply duration alignment to all stems\nprint(\"\\n=== Aligning stem durations ===\")\naligned_stems = []\n\nTARGET_DURATION = ref_info['duration']  # Use reference as target\n\nfor stem_name in STEM_NAMES:\n    input_file = f'{stem_name}_stem.wav'\n    output_file = f'{stem_name}_aligned.wav'\n    \n    # Determine strategy based on stem type\n    if stem_name in ['bass', 'drums']:\n        strategy = 'loop'  # Rhythmic elements loop well\n    elif stem_name in ['bridge', 'outro']:\n        strategy = 'crossfade'  # Sustained content benefits from crossfade\n    else:\n        strategy = 'auto'  # Let the function decide\n    \n    print(f\"Aligning {stem_name} (strategy: {strategy})...\")\n    result = align_stem_duration(input_file, output_file, TARGET_DURATION, \n                                  strategy=strategy, sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    \n    if result['success']:\n        if result['strategy'] != 'none':\n            print(f\"✓ {stem_name} aligned: {result['source_duration']:.2f}s -> {result['target_duration']:.2f}s via {result['strategy']}\")\n        else:\n            print(f\"✓ {stem_name} already aligned at {result['target_duration']:.2f}s\")\n        aligned_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} alignment FAILED: {result['error']}\")\n        raise RuntimeError(f\"Duration alignment failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(aligned_stems)} stems duration-aligned successfully\")\n```\n\n## Step 5: Generate Drum Stem Separately\n\nDrums require different processing (rhythm patterns, percussion sounds):\n\n```python\ndef generate_drum_stem(duration_sec, sample_rate, bpm, section_timing, subtype='FLOAT'):\n    \"\"\"Generate drum stem with rhythm patterns aligned to sections.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    audio_data = np.zeros(frames, dtype=np.float32)\n    beats_per_second = bpm \u002F 60.0\n    \n    # Simple kick drum pattern (every beat)\n    kick_freq = 60\n    kick_duration = 0.1\n    kick_frames = int(kick_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 1.0 \u002F beats_per_second):\n        start_frame = int(beat_time * sample_rate)\n        end_frame = min(start_frame + kick_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, kick_duration, end_frame - start_frame)\n            kick = np.exp(-5 * t) * np.sin(2 * np.pi * kick_freq * t)\n            audio_data[start_frame:end_frame] += kick * 0.9\n    \n    # Simple snare pattern (every 2nd and 4th beat)\n    snare_freq = 200\n    snare_duration = 0.05\n    snare_frames = int(snare_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 2.0 \u002F beats_per_second):\n        start_frame = int((beat_time + 0.5 \u002F beats_per_second) * sample_rate)\n        end_frame = min(start_frame + snare_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, snare_duration, end_frame - start_frame)\n            snare = np.exp(-10 * t) * np.random.uniform(-1, 1, len(t)) * 0.5\n            audio_data[start_frame:end_frame] += snare * 0.7\n    \n    audio_data = np.clip(audio_data, -1, 1)\n    \n    filepath = 'drums_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\nprint(\"\\n=== Generating drum stem ===\")\ndrums_filepath, drums_data = generate_drum_stem(TARGET_DURATION, SAMPLE_RATE, BPM, timing, subtype=SUBTYPE)\n\ndrums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\nif drums_result['success']:\n    print(f\"✓ Drum stem verified: {drums_result['info'].duration:.2f}s @ {drums_result['info'].samplerate}Hz\")\n    # Align drums if needed (usually uses loop strategy)\n    drums_aligned = 'drums_aligned.wav'\n    drums_align_result = align_stem_duration(drums_filepath, drums_aligned, TARGET_DURATION,\n                                              strategy='loop', sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    if drums_align_result['success']:\n        aligned_stems.append(drums_aligned)\n        print(f\"✓ Drums aligned via {drums_align_result['strategy']}\")\n    else:\n        print(f\"✗ Drum alignment FAILED: {drums_align_result['error']}\")\n        raise RuntimeError(f\"Drum alignment failed: {drums_align_result['error']}\")\nelse:\n    print(f\"✗ Drum stem FAILED: {drums_result['error']}\")\n    raise RuntimeError(f\"Drum stem generation failed: {drums_result['error']}\")\n```\n\n## Step 6: Apply Effects with Verification\n\nProcess each aligned stem and verify the output:\n\n```python\nfrom scipy import signal\n\ndef apply_lowpass_filter(audio_data, sample_rate, cutoff_freq=8000):\n    \"\"\"Apply lowpass filter using scipy.signal.\"\"\"\n    nyquist = sample_rate \u002F 2\n    normalized_cutoff = cutoff_freq \u002F nyquist\n    b, a = signal.butter(4, normalized_cutoff, btype='low')\n    return signal.filtfilt(b, a, audio_data)\n\ndef apply_effects_and_verify(input_filepath, output_filepath, sample_rate, subtype):\n    \"\"\"Apply effects to stem and verify output.\"\"\"\n    data, sr = sf.read(input_filepath)\n    \n    # Apply effects\n    processed = apply_lowpass_filter(data, sr, cutoff_freq=8000)\n    processed = np.clip(processed, -1, 1)\n    \n    # Export\n    sf.write(output_filepath, processed, sample_rate, subtype=subtype, format='WAV')\n    \n    # Verify\n    result = verify_stem(output_filepath, sample_rate, subtype, TARGET_DURATION, tolerance_sec=2.0)\n    return result, processed\n\nprint(\"\\n=== Applying effects to all aligned stems ===\")\nprocessed_stems = []\n\nfor aligned_file in aligned_stems:\n    stem_name = os.path.basename(aligned_file).replace('_aligned.wav', '')\n    output_file = f'{stem_name}_processed.wav'\n    \n    print(f\"Processing {stem_name}...\")\n    result, _ = apply_effects_and_verify(aligned_file, output_file, SAMPLE_RATE, SUBTYPE)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} processed and verified\")\n        processed_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} processing FAILED: {result['error']}\")\n        raise RuntimeError(f\"Effects processing failed for {stem_name}\")\n\nprint(f\"\\nAll {len(processed_stems)} stems processed successfully\")\n```\n\n## Step 7: Export Master Track\n\nMix all verified stems into master track:\n\n```python\ndef create_master_track(stem_files, output_filepath, sample_rate, subtype):\n    \"\"\"Create master track from verified stems.\"\"\"\n    # Load first stem to get dimensions\n    first_data, sr = sf.read(stem_files[0])\n    master_audio = np.zeros(len(first_data), dtype=np.float32)\n    \n    # Mix all stems with gain staging\n    gain_per_stem = 0.4  # Prevent clipping with 5 stems\n    \n    for i, stem_file in enumerate(stem_files):\n        print(f\"  Mixing stem {i+1}\u002F{len(stem_files)}: {stem_file}\")\n        data, sr = sf.read(stem_file)\n        \n        # Ensure same length as master\n        if len(data) > len(master_audio):\n            data = data[:len(master_audio)]\n        elif len(data) \u003C len(master_audio):\n            # Pad with zeros if shorter (shouldn't happen after alignment)\n            padding = np.zeros(len(master_audio) - len(data), dtype=np.float32)\n            data = np.concatenate([data, padding])\n        \n        master_audio += data * gain_per_stem\n    \n    # Apply master bus processing\n    master_audio = np.clip(master_audio, -1, 1)\n    \n    # Export master\n    sf.write(output_filepath, master_audio, sample_rate, subtype=subtype, format='WAV')\n    \n    return output_filepath, master_audio\n\nprint(\"\\n=== Creating master track ===\")\nmaster_filepath, master_data = create_master_track(processed_stems, 'master.wav', SAMPLE_RATE, SUBTYPE)\n\n# Verify master\nmaster_info = sf.info(master_filepath)\nprint(f\"Master exported: {master_filepath}\")\nprint(f\"  Duration: {master_info.duration:.2f}s\")\nprint(f\"  Sample rate: {master_info.samplerate}Hz\")\nprint(f\"  Channels: {master_info.channels}\")\nprint(f\"  Subtype: {master_info.subtype}\")\n```\n\n## Step 8: Archive and Final Verification\n\nPackage deliverables with comprehensive checks:\n\n```python\ndef create_archive(stem_files, master_file, output_archive='audio交付.zip'):\n    \"\"\"Create archive of all deliverables.\"\"\"\n    import zipfile\n    \n    all_files = stem_files + [master_file]\n    \n    with zipfile.ZipFile(output_archive, 'w', zipfile.ZIP_DEFLATED) as zipf:\n        for filepath in all_files:\n            if os.path.exists(filepath):\n                zipf.write(filepath)\n                print(f\"  Added: {filepath}\")\n    \n    return output_archive\n\ndef final_verification(master_filepath, expected_duration=None, expected_sample_rate=None):\n    \"\"\"Comprehensive final verification.\"\"\"\n    issues = []\n    \n    # Verify master file\n    if not os.path.exists(master_filepath):\n        return {'success': False, 'error': 'Master file not found'}\n    \n    info = sf.info(master_filepath)\n    \n    if expected_duration and abs(info.duration - expected_duration) > 2.0:\n        issues.append(f\"Duration mismatch: expected ~{expected_duration}s, got {info.duration}s\")\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        issues.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    # Check for clipping\n    data, _ = sf.read(master_filepath)\n    clip_ratio = np.sum(np.abs(data) >= 0.99) \u002F len(data)\n    if clip_ratio > 0.001:  # More than 0.1% clipped\n        issues.append(f\"Excessive clipping detected: {clip_ratio*100:.2f}% of samples at max level\")\n    \n    # Check for silence\n    rms = np.sqrt(np.mean(data**2))\n    if rms \u003C 0.01:\n        issues.append(f\"Audio too quiet: RMS level {rms:.4f}\")\n    \n    success = len(issues) == 0\n    \n    return {\n        'success': success,\n        'issues': issues,\n        'info': {\n            'duration': info.duration,\n            'sample_rate': info.samplerate,\n            'channels': info.channels,\n            'subtype': info.subtype,\n            'clipping_ratio': clip_ratio,\n            'rms_level': rms\n        }\n    }\n\nprint(\"\\n=== Final verification ===\")\nfinal_result = final_verification(master_filepath, expected_duration=TARGET_DURATION, \n                                   expected_sample_rate=SAMPLE_RATE)\n\nif final_result['success']:\n    print(\"✓ All verification checks passed\")\n    print(f\"  Master: {final_result['info']['duration']:.2f}s @ {final_result['info']['sample_rate']}Hz\")\n    print(f\"  RMS level: {final_result['info']['rms_level']:.4f}\")\n    print(f\"  Clipping: {final_result['info']['clipping_ratio']*100:.2f}%\")\n    \n    # Create archive\n    print(\"\\n=== Creating archive ===\")\n    archive_path = create_archive(processed_stems, master_filepath, 'audio_deliverables.zip')\n    print(f\"✓ Archive created: {archive_path}\")\nelse:\n    print(\"✗ Verification failed:\")\n    for issue in final_result['issues']:\n        print(f\"  - {issue}\")\n```\n\n## Troubleshooting\n\n### Duration Mismatch Issues\n\n**Problem**: Stems have significantly different durations causing alignment artifacts\n\n**Solutions**:\n1. **Check source generation**: Ensure all stems use the same duration parameter\n2. **Adjust strategy**: Switch from `auto` to explicit strategy based on content type\n3. **Tune crossfade parameters**: Increase `fade_duration` for smoother transitions\n4. **Enable seamless looping**: Set `loop_seamless=True` for rhythmic content\n\n### Extension Quality Issues\n\n**Problem**: Loop points audible or crossfade sounds unnatural\n\n**Solutions**:\n1. **For looping**: Find better loop points (at zero-crossings or beat boundaries)\n2. **For crossfade**: Increase overlap duration or use different source segments\n3. **For padding**: Only use for very short gaps (\u003C0.3s) at song endings\n\n### Memory Issues\n\n**Problem**: Large files cause sandbox failures\n\n**Solutions**:\n1. **Process in chunks**: Use streaming I\u002FO for very long files\n2. **Reduce sample rate**: Temporarily work at 44.1kHz, upsample for final export\n3. **Process stems sequentially**: Clear memory between stem operations\n","# Aligned Stem Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **incremental verification**, **fail-fast** principles, and **automatic duration alignment**. Each major step produces verified outputs before proceeding, with explicit handling for stem duration mismatches using appropriate extension strategies.\n\n## Overview\n\nFollow these steps in strict order. Each step must complete successfully and pass verification before proceeding to the next:\n\n1. **Early timing calculation** - Derive section transitions from BPM and duration first\n2. **Verify reference audio** - Validate input file properties and extract target duration\n3. **Generate and verify each stem individually** - One stem at a time with immediate verification\n4. **Detect and resolve duration mismatches** - Apply appropriate extension strategy (zero-pad, loop, or crossfade)\n5. **Generate drum stem separately** - Dedicated drum extension with rhythm patterns\n6. **Apply effects with verification** - Process each stem and verify output\n7. **Export master track** - Mix all verified stems\n8. **Archive and final verification** - Package deliverables with comprehensive checks\n\n## Key Differences from Standard Workflow\n\n- **Incremental verification**: Verify each stem immediately after generation, not just at the end\n- **Fail-fast approach**: Stop and report errors at each step rather than accumulating failures\n- **Early timing**: Calculate section transitions before any audio generation\n- **Duration alignment**: Explicit detection and resolution of stem duration mismatches\n- **Adaptive extension**: Choose appropriate strategy (zero-pad\u002Floop\u002Fcrossfade) based on stem type\n- **Separated drums**: Drum stem generation is a distinct step with rhythm-specific processing\n- **Memory-efficient**: Process stems individually to avoid large array operations that cause sandbox failures\n\n## Step 1: Calculate Timing Parameters (Early)\n\nCalculate all timing parameters **before** generating any audio. This ensures consistent timing across all stems:\n\n```python\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    \"\"\"Calculate beat-aligned transition points for song sections.\"\"\"\n    beats_per_second = bpm \u002F 60.0\n    \n    section_durations = {}\n    cumulative_time = 0\n    \n    for section_name, beat_count in sections.items():\n        duration = beat_count \u002F beats_per_second\n        section_durations[section_name] = {\n            'start': cumulative_time,\n            'end': cumulative_time + duration,\n            'beats': beat_count,\n            'start_beat': cumulative_time * beats_per_second\n        }\n        cumulative_time += duration\n    \n    return section_durations\n\n# Configuration\nBPM = 120\nDURATION = 137\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ntiming = calculate_section_transitions(BPM, DURATION, SECTIONS)\nprint(\"Timing calculated:\")\nfor section, data in timing.items():\n    print(f\"  {section}: {data['start']:.2f}s - {data['end']:.2f}s ({data['beats']} beats)\")\n```\n\n## Step 2: Verify Reference Audio\n\nValidate the reference file exists and has expected properties:\n\n```python\nimport soundfile as sf\nimport os\n\ndef verify_reference_file(filepath, expected_sample_rate=None, min_duration=None):\n    \"\"\"Verify reference audio file and return info dict.\"\"\"\n    if not os.path.exists(filepath):\n        raise FileNotFoundError(f\"Reference file not found: {filepath}\")\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        errors.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f\"Duration too short: expected >= {min_duration}s, got {info.duration}s\")\n    \n    if errors:\n        raise ValueError(f\"Reference file validation failed: {'; '.join(errors)}\")\n    \n    print(f\"Reference verified: {info.duration:.2f}s @ {info.samplerate}Hz, {info.channels}ch, {info.subtype}\")\n    return {\n        'sample_rate': info.samplerate,\n        'duration': info.duration,\n        'channels': info.channels,\n        'subtype': info.subtype\n    }\n\n# Verify reference\nref_info = verify_reference_file('reference.wav', expected_sample_rate=48000, min_duration=130)\nTARGET_DURATION = ref_info['duration']  # Use actual reference duration as target\n```\n\n## Step 3: Generate and Verify Each Stem Individually\n\nGenerate one stem at a time, verify it immediately before proceeding to the next:\n\n```python\nimport numpy as np\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT', section_timing=None):\n    \"\"\"Generate a single stem with explicit sample type.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    \n    # Generate stem-specific content (customize per stem type)\n    if name == 'bass':\n        freq = 110  # A2\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.8\n    elif name == 'guitars':\n        freq = 440  # A4\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.6\n    elif name == 'synths':\n        freq = 880  # A5\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.5\n    elif name == 'bridge':\n        freq = 220  # A3\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.7\n    else:\n        audio_data = np.sin(2 * np.pi * 440 * t) * 0.5\n    \n    # Ensure proper data type\n    if subtype == 'FLOAT':\n        audio_data = audio_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        audio_data = np.clip(audio_data, -1, 1) * (2**23 - 1)\n        audio_data = audio_data.astype(np.int32)\n    \n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\ndef verify_stem(filepath, expected_sample_rate, expected_subtype, expected_duration, tolerance_sec=1.0):\n    \"\"\"Verify a single stem meets specifications.\"\"\"\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if info.subtype != expected_subtype:\n        errors.append(f'subtype: expected {expected_subtype}, got {info.subtype}')\n    \n    if abs(info.duration - expected_duration) > tolerance_sec:\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    # Calculate duration discrepancy\n    duration_diff = info.duration - expected_duration\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors), 'duration_diff': duration_diff}\n    \n    return {'success': True, 'info': info, 'duration_diff': duration_diff}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSUBTYPE = 'FLOAT'\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\nstem_info = {}  # Track duration discrepancies\n\nfor stem_name in STEM_NAMES:\n    print(f\"\\n=== Generating {stem_name} stem ===\")\n    \n    # Generate\n    filepath, data = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype=SUBTYPE)\n    \n    # Verify immediately\n    result = verify_stem(filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} stem verified: {result['info'].duration:.2f}s @ {result['info'].samplerate}Hz\")\n        if abs(result['duration_diff']) > 0.1:\n            print(f\"  ⚠ Duration discrepancy: {result['duration_diff']:+.2f}s\")\n        generated_stems.append(filepath)\n        stem_info[stem_name] = result\n    else:\n        print(f\"✗ {stem_name} stem FAILED: {result['error']}\")\n        raise RuntimeError(f\"Stem generation failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(generated_stems)} stems generated and verified successfully\")\n```\n\n## Step 4: Detect and Resolve Duration Mismatches\n\nWhen stems have different durations, apply the appropriate extension strategy:\n\n### Strategy Selection Guidelines\n\n| Strategy | Best For | Duration Gap | Sound Characteristic |\n|----------|----------|--------------|---------------------|\n| **Zero-padding** | Short gaps (\u003C0.5s), silence sections, endings | Small | Clean, abrupt |\n| **Looping** | Repetitive patterns (drums, bass, rhythmic elements) | Medium to large | Seamless, rhythmic |\n| **Crossfade extension** | Melodic content, sustained instruments, vocals | Any | Natural, smooth |\n\n```python\ndef align_stem_duration(input_filepath, output_filepath, target_duration, strategy='auto', \n                        sample_rate=None, subtype='FLOAT', loop_seamless=True):\n    \"\"\"\n    Align stem duration to target using appropriate strategy.\n    \n    Args:\n        input_filepath: Path to source stem\n        output_filepath: Path for aligned output\n        target_duration: Target duration in seconds\n        strategy: 'zero_pad', 'loop', 'crossfade', or 'auto'\n        sample_rate: Sample rate (auto-detected if None)\n        subtype: Audio subtype\n        loop_seamless: Apply crossfade at loop boundaries if True\n    \n    Returns:\n        dict with success status and alignment details\n    \"\"\"\n    if not os.path.exists(input_filepath):\n        return {'success': False, 'error': f'Input file not found: {input_filepath}'}\n    \n    # Load source\n    data, sr = sf.read(input_filepath)\n    if sample_rate is None:\n        sample_rate = sr\n    \n    source_duration = len(data) \u002F sample_rate\n    duration_diff = target_duration - source_duration\n    \n    # If already aligned (within tolerance), just copy\n    if abs(duration_diff) \u003C 0.01:\n        sf.write(output_filepath, data, sample_rate, subtype=subtype, format='WAV')\n        return {'success': True, 'strategy': 'none', 'duration_diff': 0}\n    \n    if duration_diff > 0:\n        # Need to EXTEND\n        extend_frames = int(duration_diff * sample_rate)\n        \n        if strategy == 'auto':\n            # Auto-select based on duration gap and stem type\n            if duration_diff \u003C 0.5:\n                strategy = 'zero_pad'\n            elif 'drum' in input_filepath or 'bass' in input_filepath:\n                strategy = 'loop'\n            else:\n                strategy = 'crossfade'\n        \n        if strategy == 'zero_pad':\n            # Append zeros\n            padding = np.zeros(extend_frames, dtype=data.dtype)\n            aligned_data = np.concatenate([data, padding])\n            \n        elif strategy == 'loop':\n            # Loop the content\n            loop_frames = len(data)\n            loops_needed = int(np.ceil(extend_frames \u002F loop_frames))\n            \n            if loop_seamless and loops_needed > 1:\n                # Apply crossfade at loop boundaries for seamless looping\n                crossfade_frames = min(int(0.05 * sample_rate), loop_frames \u002F\u002F 4)\n                loop_extension = np.zeros(extend_frames, dtype=data.dtype)\n                \n                for i in range(loops_needed):\n                    start = i * loop_frames\n                    end = min(start + loop_frames, extend_frames)\n                    actual_len = end - start\n                    \n                    # Extract loop segment\n                    loop_segment = data[:actual_len].copy()\n                    \n                    # Apply crossfade at boundaries\n                    if i > 0 and actual_len >= crossfade_frames * 2:\n                        # Fade in from previous loop\n                        fade_in = np.linspace(0, 1, crossfade_frames)\n                        loop_segment[:crossfade_frames] *= fade_in\n                    \n                    if i \u003C loops_needed - 1 and actual_len >= crossfade_frames * 2:\n                        # Fade out for next loop\n                        fade_out = np.linspace(1, 0, crossfade_frames)\n                        loop_segment[-crossfade_frames:] *= fade_out\n                    \n                    loop_extension[start:end] = loop_segment\n                \n                extend_frames_actual = len(loop_extension)\n            else:\n                # Simple tiling\n                loop_extension = np.tile(data, loops_needed)[:extend_frames]\n                extend_frames_actual = extend_frames\n            \n            aligned_data = np.concatenate([data, loop_extension[:extend_frames_actual]])\n            \n        elif strategy == 'crossfade':\n            # Extend using crossfade from the end of the source\n            # Take last portion and crossfade it onto itself\n            fade_duration = min(duration_diff * 0.3, 2.0)  # 30% of gap, max 2s\n            fade_frames = int(fade_duration * sample_rate)\n            \n            if fade_frames >= len(data) \u002F\u002F 2:\n                # Source too short for crossfade, fall back to loop\n                fade_frames = len(data) \u002F\u002F 4\n            \n            # Extract tail segment for extension\n            tail_segment = data[-fade_frames:].copy()\n            \n            # Create extended portion with crossfade\n            extended_portion = np.zeros(extend_frames, dtype=data.dtype)\n            \n            if extend_frames \u003C= fade_frames:\n                # Short extension: just crossfade tail onto itself\n                fade_in = np.linspace(0, 1, extend_frames)\n                extended_portion = tail_segment[:extend_frames] * fade_in\n            else:\n                # Longer extension: loop tail with crossfades\n                loops = int(np.ceil(extend_frames \u002F fade_frames))\n                for i in range(loops):\n                    start = i * fade_frames\n                    end = min(start + fade_frames, extend_frames)\n                    seg_len = end - start\n                    \n                    segment = tail_segment[:seg_len].copy()\n                    \n                    # Crossfade boundaries\n                    if seg_len >= 100:\n                        cf_len = min(50, seg_len \u002F\u002F 4)\n                        if i > 0:\n                            fade_in = np.linspace(0, 1, cf_len)\n                            segment[:cf_len] *= fade_in\n                    \n                    extended_portion[start:end] = segment\n            \n            aligned_data = np.concatenate([data, extended_portion])\n        \n        else:\n            return {'success': False, 'error': f'Unknown extension strategy: {strategy}'}\n        \n    else:\n        # Need to TRUNCATE\n        truncate_frames = int(abs(duration_diff) * sample_rate)\n        aligned_data = data[:len(data) - truncate_frames]\n        strategy = 'truncate'\n    \n    # Ensure proper data type and clip\n    if subtype == 'FLOAT':\n        aligned_data = aligned_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        aligned_data = np.clip(aligned_data, -1, 1) * (2**23 - 1)\n        aligned_data = aligned_data.astype(np.int32)\n    else:\n        aligned_data = np.clip(aligned_data, -1, 1)\n    \n    # Export aligned stem\n    sf.write(output_filepath, aligned_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return {\n        'success': True, \n        'strategy': strategy,\n        'source_duration': source_duration,\n        'target_duration': target_duration,\n        'duration_diff': duration_diff,\n        'aligned_frames': len(aligned_data)\n    }\n\n# Apply duration alignment to all stems\nprint(\"\\n=== Aligning stem durations ===\")\naligned_stems = []\n\nTARGET_DURATION = ref_info['duration']  # Use reference as target\n\nfor stem_name in STEM_NAMES:\n    input_file = f'{stem_name}_stem.wav'\n    output_file = f'{stem_name}_aligned.wav'\n    \n    # Determine strategy based on stem type\n    if stem_name in ['bass', 'drums']:\n        strategy = 'loop'  # Rhythmic elements loop well\n    elif stem_name in ['bridge', 'outro']:\n        strategy = 'crossfade'  # Sustained content benefits from crossfade\n    else:\n        strategy = 'auto'  # Let the function decide\n    \n    print(f\"Aligning {stem_name} (strategy: {strategy})...\")\n    result = align_stem_duration(input_file, output_file, TARGET_DURATION, \n                                  strategy=strategy, sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    \n    if result['success']:\n        if result['strategy'] != 'none':\n            print(f\"✓ {stem_name} aligned: {result['source_duration']:.2f}s -> {result['target_duration']:.2f}s via {result['strategy']}\")\n        else:\n            print(f\"✓ {stem_name} already aligned at {result['target_duration']:.2f}s\")\n        aligned_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} alignment FAILED: {result['error']}\")\n        raise RuntimeError(f\"Duration alignment failed for {stem_name}: {result['error']}\")\n\nprint(f\"\\nAll {len(aligned_stems)} stems duration-aligned successfully\")\n```\n\n## Step 5: Generate Drum Stem Separately\n\nDrums require different processing (rhythm patterns, percussion sounds):\n\n```python\ndef generate_drum_stem(duration_sec, sample_rate, bpm, section_timing, subtype='FLOAT'):\n    \"\"\"Generate drum stem with rhythm patterns aligned to sections.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    audio_data = np.zeros(frames, dtype=np.float32)\n    beats_per_second = bpm \u002F 60.0\n    \n    # Simple kick drum pattern (every beat)\n    kick_freq = 60\n    kick_duration = 0.1\n    kick_frames = int(kick_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 1.0 \u002F beats_per_second):\n        start_frame = int(beat_time * sample_rate)\n        end_frame = min(start_frame + kick_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, kick_duration, end_frame - start_frame)\n            kick = np.exp(-5 * t) * np.sin(2 * np.pi * kick_freq * t)\n            audio_data[start_frame:end_frame] += kick * 0.9\n    \n    # Simple snare pattern (every 2nd and 4th beat)\n    snare_freq = 200\n    snare_duration = 0.05\n    snare_frames = int(snare_duration * sample_rate)\n    \n    for beat_time in np.arange(0, duration_sec, 2.0 \u002F beats_per_second):\n        start_frame = int((beat_time + 0.5 \u002F beats_per_second) * sample_rate)\n        end_frame = min(start_frame + snare_frames, frames)\n        \n        if start_frame \u003C frames:\n            t = np.linspace(0, snare_duration, end_frame - start_frame)\n            snare = np.exp(-10 * t) * np.random.uniform(-1, 1, len(t)) * 0.5\n            audio_data[start_frame:end_frame] += snare * 0.7\n    \n    audio_data = np.clip(audio_data, -1, 1)\n    \n    filepath = 'drums_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\nprint(\"\\n=== Generating drum stem ===\")\ndrums_filepath, drums_data = generate_drum_stem(TARGET_DURATION, SAMPLE_RATE, BPM, timing, subtype=SUBTYPE)\n\ndrums_result = verify_stem(drums_filepath, SAMPLE_RATE, SUBTYPE, TARGET_DURATION)\nif drums_result['success']:\n    print(f\"✓ Drum stem verified: {drums_result['info'].duration:.2f}s @ {drums_result['info'].samplerate}Hz\")\n    # Align drums if needed (usually uses loop strategy)\n    drums_aligned = 'drums_aligned.wav'\n    drums_align_result = align_stem_duration(drums_filepath, drums_aligned, TARGET_DURATION,\n                                              strategy='loop', sample_rate=SAMPLE_RATE, subtype=SUBTYPE)\n    if drums_align_result['success']:\n        aligned_stems.append(drums_aligned)\n        print(f\"✓ Drums aligned via {drums_align_result['strategy']}\")\n    else:\n        print(f\"✗ Drum alignment FAILED: {drums_align_result['error']}\")\n        raise RuntimeError(f\"Drum alignment failed: {drums_align_result['error']}\")\nelse:\n    print(f\"✗ Drum stem FAILED: {drums_result['error']}\")\n    raise RuntimeError(f\"Drum stem generation failed: {drums_result['error']}\")\n```\n\n## Step 6: Apply Effects with Verification\n\nProcess each aligned stem and verify the output:\n\n```python\nfrom scipy import signal\n\ndef apply_lowpass_filter(audio_data, sample_rate, cutoff_freq=8000):\n    \"\"\"Apply lowpass filter using scipy.signal.\"\"\"\n    nyquist = sample_rate \u002F 2\n    normalized_cutoff = cutoff_freq \u002F nyquist\n    b, a = signal.butter(4, normalized_cutoff, btype='low')\n    return signal.filtfilt(b, a, audio_data)\n\ndef apply_effects_and_verify(input_filepath, output_filepath, sample_rate, subtype):\n    \"\"\"Apply effects to stem and verify output.\"\"\"\n    data, sr = sf.read(input_filepath)\n    \n    # Apply effects\n    processed = apply_lowpass_filter(data, sr, cutoff_freq=8000)\n    processed = np.clip(processed, -1, 1)\n    \n    # Export\n    sf.write(output_filepath, processed, sample_rate, subtype=subtype, format='WAV')\n    \n    # Verify\n    result = verify_stem(output_filepath, sample_rate, subtype, TARGET_DURATION, tolerance_sec=2.0)\n    return result, processed\n\nprint(\"\\n=== Applying effects to all aligned stems ===\")\nprocessed_stems = []\n\nfor aligned_file in aligned_stems:\n    stem_name = os.path.basename(aligned_file).replace('_aligned.wav', '')\n    output_file = f'{stem_name}_processed.wav'\n    \n    print(f\"Processing {stem_name}...\")\n    result, _ = apply_effects_and_verify(aligned_file, output_file, SAMPLE_RATE, SUBTYPE)\n    \n    if result['success']:\n        print(f\"✓ {stem_name} processed and verified\")\n        processed_stems.append(output_file)\n    else:\n        print(f\"✗ {stem_name} processing FAILED: {result['error']}\")\n        raise RuntimeError(f\"Effects processing failed for {stem_name}\")\n\nprint(f\"\\nAll {len(processed_stems)} stems processed successfully\")\n```\n\n## Step 7: Export Master Track\n\nMix all verified stems into master track:\n\n```python\ndef create_master_track(stem_files, output_filepath, sample_rate, subtype):\n    \"\"\"Create master track from verified stems.\"\"\"\n    # Load first stem to get dimensions\n    first_data, sr = sf.read(stem_files[0])\n    master_audio = np.zeros(len(first_data), dtype=np.float32)\n    \n    # Mix all stems with gain staging\n    gain_per_stem = 0.4  # Prevent clipping with 5 stems\n    \n    for i, stem_file in enumerate(stem_files):\n        print(f\"  Mixing stem {i+1}\u002F{len(stem_files)}: {stem_file}\")\n        data, sr = sf.read(stem_file)\n        \n        # Ensure same length as master\n        if len(data) > len(master_audio):\n            data = data[:len(master_audio)]\n        elif len(data) \u003C len(master_audio):\n            # Pad with zeros if shorter (shouldn't happen after alignment)\n            padding = np.zeros(len(master_audio) - len(data), dtype=np.float32)\n            data = np.concatenate([data, padding])\n        \n        master_audio += data * gain_per_stem\n    \n    # Apply master bus processing\n    master_audio = np.clip(master_audio, -1, 1)\n    \n    # Export master\n    sf.write(output_filepath, master_audio, sample_rate, subtype=subtype, format='WAV')\n    \n    return output_filepath, master_audio\n\nprint(\"\\n=== Creating master track ===\")\nmaster_filepath, master_data = create_master_track(processed_stems, 'master.wav', SAMPLE_RATE, SUBTYPE)\n\n# Verify master\nmaster_info = sf.info(master_filepath)\nprint(f\"Master exported: {master_filepath}\")\nprint(f\"  Duration: {master_info.duration:.2f}s\")\nprint(f\"  Sample rate: {master_info.samplerate}Hz\")\nprint(f\"  Channels: {master_info.channels}\")\nprint(f\"  Subtype: {master_info.subtype}\")\n```\n\n## Step 8: Archive and Final Verification\n\nPackage deliverables with comprehensive checks:\n\n```python\ndef create_archive(stem_files, master_file, output_archive='audio交付.zip'):\n    \"\"\"Create archive of all deliverables.\"\"\"\n    import zipfile\n    \n    all_files = stem_files + [master_file]\n    \n    with zipfile.ZipFile(output_archive, 'w', zipfile.ZIP_DEFLATED) as zipf:\n        for filepath in all_files:\n            if os.path.exists(filepath):\n                zipf.write(filepath)\n                print(f\"  Added: {filepath}\")\n    \n    return output_archive\n\ndef final_verification(master_filepath, expected_duration=None, expected_sample_rate=None):\n    \"\"\"Comprehensive final verification.\"\"\"\n    issues = []\n    \n    # Verify master file\n    if not os.path.exists(master_filepath):\n        return {'success': False, 'error': 'Master file not found'}\n    \n    info = sf.info(master_filepath)\n    \n    if expected_duration and abs(info.duration - expected_duration) > 2.0:\n        issues.append(f\"Duration mismatch: expected ~{expected_duration}s, got {info.duration}s\")\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        issues.append(f\"Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}\")\n    \n    # Check for clipping\n    data, _ = sf.read(master_filepath)\n    clip_ratio = np.sum(np.abs(data) >= 0.99) \u002F len(data)\n    if clip_ratio > 0.001:  # More than 0.1% clipped\n        issues.append(f\"Excessive clipping detected: {clip_ratio*100:.2f}% of samples at max level\")\n    \n    # Check for silence\n    rms = np.sqrt(np.mean(data**2))\n    if rms \u003C 0.01:\n        issues.append(f\"Audio too quiet: RMS level {rms:.4f}\")\n    \n    success = len(issues) == 0\n    \n    return {\n        'success': success,\n        'issues': issues,\n        'info': {\n            'duration': info.duration,\n            'sample_rate': info.samplerate,\n            'channels': info.channels,\n            'subtype': info.subtype,\n            'clipping_ratio': clip_ratio,\n            'rms_level': rms\n        }\n    }\n\nprint(\"\\n=== Final verification ===\")\nfinal_result = final_verification(master_filepath, expected_duration=TARGET_DURATION, \n                                   expected_sample_rate=SAMPLE_RATE)\n\nif final_result['success']:\n    print(\"✓ All verification checks passed\")\n    print(f\"  Master: {final_result['info']['duration']:.2f}s @ {final_result['info']['sample_rate']}Hz\")\n    print(f\"  RMS level: {final_result['info']['rms_level']:.4f}\")\n    print(f\"  Clipping: {final_result['info']['clipping_ratio']*100:.2f}%\")\n    \n    # Create archive\n    print(\"\\n=== Creating archive ===\")\n    archive_path = create_archive(processed_stems, master_filepath, 'audio_deliverables.zip')\n    print(f\"✓ Archive created: {archive_path}\")\nelse:\n    print(\"✗ Verification failed:\")\n    for issue in final_result['issues']:\n        print(f\"  - {issue}\")\n```\n\n## Troubleshooting\n\n### Duration Mismatch Issues\n\n**Problem**: Stems have significantly different durations causing alignment artifacts\n\n**Solutions**:\n1. **Check source generation**: Ensure all stems use the same duration parameter\n2. **Adjust strategy**: Switch from `auto` to explicit strategy based on content type\n3. **Tune crossfade parameters**: Increase `fade_duration` for smoother transitions\n4. **Enable seamless looping**: Set `loop_seamless=True` for rhythmic content\n\n### Extension Quality Issues\n\n**Problem**: Loop points audible or crossfade sounds unnatural\n\n**Solutions**:\n1. **For looping**: Find better loop points (at zero-crossings or beat boundaries)\n2. **For crossfade**: Increase overlap duration or use different source segments\n3. **For padding**: Only use for very short gaps (\u003C0.3s) at song endings\n\n### Memory Issues\n\n**Problem**: Large files cause sandbox failures\n\n**Solutions**:\n1. **Process in chunks**: Use streaming I\u002FO for very long files\n2. **Reduce sample rate**: Temporarily work at 44.1kHz, upsample for final export\n3. **Process stems sequentially**: Clear memory between stem operations\n",{"name":5,"description":7},"main","ff671ef61ed6587c49bd54c81cdc751c0b99e363","gdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace","https:\u002F\u002Fgithub.com\u002FAG064","AG064, E.Mi.\r\n\r\nA person who thinks all the time, yet all they have to think about is nothing. I want to improve the world and work on open source projects","2026-10-08 06:53:48",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add AG064\u002FOpenSpace --skill aligned-stem-workflow",{"tool":54,"command":55},"bunx","bunx skills add AG064\u002FOpenSpace --skill aligned-stem-workflow",{"tool":57,"command":58},"pnpm","pnpm dlx skills add AG064\u002FOpenSpace --skill aligned-stem-workflow","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced\u002FSKILL.md",true,[62],{"path":63,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":66,"sourceHtmlUrl":67},".skill_id","OTHER","其他",54,"https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fgdpval_bench\u002Fskills\u002Faudio-track-production-enhanced-enhanced\u002F.skill_id",[69,93,108,117,147,163],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":36},"01M6KKMPWA0B5SCCH766F8M5EA","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92],"write special chars ts check","check","write","filters","Existing","type-checking","for","errors","script","output","type","files","only","template","file","python","typescript",{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":36},"01M6KKMJXVBNVEY3TRK055F4A7","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[100,101,78,89,102,103,90,91,104,28,105,106,107,82,84,34],"readback","write special chars readback","cleanup","read","scripts","via","post","helper",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":36},"01M6KKMEGX9M9NC105J0W3Q5B9","write-special-chars-heredoc","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) by using a Python heredoc script executed via shell.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-heredoc\u002FSKILL.md",[],[78,115,91,82,105,89,116,90,84],"write special chars heredoc","shell",{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":128,"publishedAt":36},"01M6KKM8EJ2AATVHZBNB916WT0","worldmonitor-reference","Curated architecture index of the WorldMonitor open-source dashboard. Reference for extracting patterns — vanilla TypeScript, Panel class hierarchy, service layer, CSS grid, API edge functions, refresh scheduler, and 60+ data source integrations.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fworldmonitor-reference\u002FSKILL.md",[123],{"categoryNo":124,"categoryName":125,"taxonomyType":126,"taxonomyTypeDesc":127},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[129,130,131,132,92,133,134,135,136,137,82,138,139,140,141,142,143,144,145,146],"reference","worldmonitor","worldmonitor reference","dashboard","css","architecture","extracting","hierarchy","source","layer","panel","patterns","edge functions","integrations","open","api","data","scheduler",{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":151,"categories":152,"keywords":153,"publishedAt":36},"01M6KKM39PHYK627F19GE2B9XN","virtual-list","Implement efficient virtual scrolling for rendering large lists with DOM recycling, chunk-based rendering, and performance optimizations","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fvirtual-list\u002FSKILL.md",[],[154,155,156,157,82,158,34,159,160,161,162],"virtual list","list","virtual","chunk","dom","rendering","recycling","implement","performance",{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":169,"publishedAt":36},"01M6KKKY7T2P61Y0JH54CDEJKQ","verify-directory-structure","Diagnose and resolve file access issues by first verifying the directory structure.","https:\u002F\u002Fgithub.com\u002FAG064\u002FOpenSpace\u002Fblob\u002Fmain\u002Fshowcase\u002Fskills\u002Fverify-directory-structure\u002FSKILL.md",[],[170,171,172,173,174,175,90,176,177,178],"directory","verify","structure","verify directory structure","access","first","issues","diagnose","file access"]