Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

estsources = model.separatefile(path=audio_file) 这行语句分出了很多个

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with grok-3-mini-beta’s answer.
  1. User

    est_sources = model.separate_file(path=audio_file) 这行语句分出了很多个

  2. Claude Assistant

    你说得对!model.separate_file() 返回的 est_sources 是一个张量,它的形状通常是 [samples, sources]。让我详细解释一下这个输出,并提供正确的处理方法。

    理解 Sepformer 的输出

    # 检查输出的形状
    print(f"est_sources shape: {est_sources.shape}")
    # 例如输出: torch.Size([160000, 2])
    # 其中 160000 是音频采样点数(10秒 × 16000Hz采样率)
    # 2 是分离出的音源数量
    

    正确的处理方法

    from speechbrain.pretrained import SepformerSeparation as separator
    import torchaudio
    import soundfile as sf
    import torch
    import os
    
    def separate_sources(audio_file, output_dir="separated_tracks"):
        """
        使用 Sepformer 分离重叠语音
        """
        print("Starting source separation...")
        
        # 加载模型
        model = separator.from_hparams(
            source="speechbrain/sepformer-wham", 
            savedir="pretrained_models/sepformer-wham",
            run_opts={"device": "cuda" if torch.cuda.is_available() else "cpu"}
        )
        
        # 执行分离
        est_sources = model.separate_file(path=audio_file)
        
        # 检查输出形状
        print(f"Separated audio shape: {est_sources.shape}")
        # est_sources.shape = [采样点数, 音源数]
        
        # 获取采样率(Sepformer-wham 默认是 8000Hz)
        sample_rate = 8000  # 或者从模型配置中获取
        
        os.makedirs(output_dir, exist_ok=True)
        
        # 获取音源数量(通常是2)
        num_sources = est_sources.shape[1]
        
        track_paths = []
        
        # 正确地保存每个分离的音轨
        for i in range(num_sources):
            # 提取第 i 个音源的所有采样点
            source_audio = est_sources[:, i].cpu().numpy()
            
            # 保存为 WAV 文件
            track_path = os.path.join(output_dir, f"source_{i+1}.wav")
            sf.write(track_path, source_audio, sample_rate)
            
            track_paths.append(track_path)
            print(f"Saved track {i+1}/{num_sources}: {track_path}")
            
            # 可选:打印每个音轨的时长
            duration = len(source_audio) / sample_rate
            print(f"  Duration: {duration:.2f} seconds")
        
        return track_paths
    
    def resample_audio_if_needed(audio_path, target_sr=16000):
        """
        将音频重采样到目标采样率(Whisper 需要 16kHz)
        """
        # 加载音频
        waveform, sr = torchaudio.load(audio_path)
        
        # 如果采样率不匹配,进行重采样
        if sr != target_sr:
            resampler = torchaudio.transforms.Resample(sr, target_sr)
            waveform = resampler(waveform)
            
            # 保存重采样后的音频
            resampled_path = audio_path.replace('.wav', f'_{target_sr}hz.wav')
            torchaudio.save(resampled_path, waveform, target_sr)
            return resampled_path
        
        return audio_path
    
    # 完整的处理流程
    def process_with_separation(audio_file):
        """
        1. 分离音源
        2. 重采样(如果需要)
        3. 对每个音轨运行 WhisperX
        """
        # 步骤1:分离音源
        separated_tracks = separate_sources(audio_file)
        
        results = []
        
        # 步骤2&3:处理每个分离的音轨
        for i, track_path in enumerate(separated_tracks):
            print(f"\nProcessing track {i+1}...")
            
            # Sepformer-wham 输出是 8kHz,但 Whisper 需要 16kHz
            resampled_path = resample_audio_if_needed(track_path, target_sr=16000)
            
            # 对这个音轨运行 WhisperX
            # (这里调用你之前的 WhisperX 代码)
            track_result = run_whisperx_on_file(resampled_path)
            
            # 为结果添加音轨标记
            for segment in track_result["segments"]:
                segment["track"] = i + 1
            
            results.append(track_result)
        
        return results
    
    def run_whisperx_on_file(audio_file):
        """
        封装的 WhisperX 处理函数
        """
        import whisperx
        
        device = "cuda" if torch.cuda.is_available() else "cpu"
        
        # 加载模型
        model = whisperx.load_model("large-v3", device, compute_type="float16", language="ja")
        
        # 加载音频
        audio = whisperx.load_audio(audio_file)
        
        # 执行 ASR
        result = model.transcribe(audio, batch_size=8)
        
        # 释放内存
        del model
        torch.cuda.empty_cache()
        
        return result
    

    关于 Sepformer 的重要说明

    1. 默认分离数量:Sepformer-wham 模型默认分离成 2 个音源。这是因为它是在 2-speaker 混合数据集上训练的。

    2. 采样率问题:

      • Sepformer-wham 使用 8kHz 采样率
      • Whisper 需要 16kHz 采样率
      • 所以需要重采样步骤
    3. 如果需要分离更多说话人:

      # 使用 LibriMix 版本,支持 3 个说话人
      model = separator.from_hparams(
          source="speechbrain/sepformer-libri3mix",
          savedir="pretrained_models/sepformer-libri3mix"
      )
      

    处理多个音轨的结果

    分离后,你需要决定如何合并多个音轨的识别结果:

    def merge_multi_track_results(results_list):
        """
        合并多个音轨的识别结果,按时间排序
        """
        all_segments = []
        
        for track_idx, result in enumerate(results_list):
            for segment in result["segments"]:
                # 添加音轨信息
                segment["track"] = track_idx + 1
                all_segments.append(segment)
        
        # 按开始时间排序
        all_segments.sort(key=lambda x: x["start"])
        
        # 可选:合并时间上重叠的片段
        merged = []
        for seg in all_segments:
            if not merged or seg["start"] > merged[-1]["end"] + 0.1:
                merged.append(seg)
            else:
                # 处理重叠:可以选择合并文本或保留两个
                # 这里示例:如果来自不同音轨,说明是同时说话
                if seg["track"] != merged[-1]["track"]:
                    # 标记为同时说话
                    merged[-1]["text"] += f" [同时-轨道{seg['track']}]: {seg['text']}"
        
        return merged
    

    简化方案(如果只需要处理 2 人对话)

    如果你的广播剧主要是 2 人对话,可以直接使用默认的 Sepformer-wham:

    # 快速使用示例
    separated_tracks = separate_sources("drama.mp3")
    print(f"分离出 {len(separated_tracks)} 个音轨")
    # 输出: 分离出 2 个音轨
    

    这样就能正确处理分离出的音频了。每个音轨包含一个主要说话人的声音,可以分别进行识别和处理。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.