我无法在M1 Macbook的Python上播放任何音频

0 投票
1 回答
45 浏览
提问于 2025-04-14 16:18

我正在用Python生成一个信号扫描(MLS),并测量一个房间的脉冲响应。我已经成功运行了代码,并且可以绘制脉冲响应的图。但是我遇到的问题是听不到声音。我运行代码时什么也听不见,图表也是平的,因为没有声音被发出或录制。目前我在使用我的M1 Macbook Pro,没有连接任何外部音频设备。

import numpy as np
import matplotlib.pyplot as plt
import sounddevice as sd

def generate_mls(length):
    # Generate Maximum Length Sequence (MLS)
    n = int(np.log2(length)) - 1
    sequence = np.random.randint(0, 2, size=(2 ** n) - 1)
    mls = np.array(sequence.tolist() * int(length / (2 ** n - 1)), dtype=np.float32)
    mls -= 0.5
    mls *= 2
    return mls

def play_and_capture(mls, sample_rate):
    print("Playing MLS...")
    sd.play(mls, samplerate=sample_rate, blocking=True)
    print("Recording...")
    recording = sd.rec(len(mls), samplerate=sample_rate, channels=1, dtype='float64')
    sd.wait()  # Wait until recording is finished
    print("Recording finished.")
    return recording.flatten()

def plot_impulse_response(impulse_response, sample_rate):
    time = np.arange(len(impulse_response)) / sample_rate
    plt.figure(figsize=(10, 6))
    plt.plot(time, impulse_response)
    plt.xlabel('Time (s)')
    plt.ylabel('Amplitude')
    plt.title('Room Impulse Response')
    plt.grid(True)
    plt.show()

# Define parameters
length = 2**15  # Length of MLS signal
sample_rate = 44100  # Hz

# Generate MLS
mls = generate_mls(length)

# Play MLS and capture the response
impulse_response = play_and_capture(mls, sample_rate)

# Plot the impulse response
plot_impulse_response(impulse_response, sample_rate)

1 个回答

0

我在一个虚拟环境中运行代码,当我在本地电脑的终端窗口中运行时,代码成功执行了,我可以听到声音并进行录音。

撰写回答