繁体   English   中英

Python:PCM音频操作-使用结构时左声道嘈杂

[英]Python: PCM audio manipulation - noisy left channel while using struct

这是我的第一个代码。 我编写了一个程序,该程序必须使用幅度调制概念来处理未压缩的PCM文件。

我现在面临的问题是我在右声道获得正确的音频输出,而在左声道获得完整的噪声。

我知道立体声PCM文件的交错格式,如果我想在两个通道上调制声音,我只需要处理每个样本。 有什么建议吗? 这是我的代码:

import threading
import pyaudio
import struct
import numpy as npy
import wave

CHUNK = 1  # Number of samples to read
modulator_frequency: float = 12800.0  # Modulation frequency in Hz

# input_file = input(r"Specify *.wav audio file: ")
# data = wave.open(input_file, "rb")

data = wave.open("walk on air.wav", "rb")

pya = pyaudio.PyAudio()  # Load PyAudio module

audio_stream = pya.open(format=pya.get_format_from_width(data.getsampwidth()),
                        channels=data.getnchannels(),
                        rate=data.getframerate(),
                        output=True)


def play_stream():
    bytestream = data.readframes(CHUNK)

    t = 1  # Iterating sample number

    while bytestream:  # Play until bytestream ends
        x = struct.unpack(b'<i', bytestream)[0]  # Convert b'\x01\x00\xfd\xff' to some friendly numbers
        # print(x)
        y = int(x * npy.sin(2 * npy.pi * modulator_frequency * t / data.getframerate()).astype(npy.float32))
        # y = x
        t += 1
        z = struct.pack(b'<i', y)  # Convert friendly numbers back to bytestream
        # print(bytestream, " ---> ", x, " ---> ", y, " ---> ", z)
        bytestream = data.readframes(CHUNK)
        audio_stream.write(z)


if data.getsampwidth() == 3:
    sample_type = "24 Bit Integer PCM"
elif data.getsampwidth() == 2:
    sample_type = "16 Bit Integer PCM"
elif data.getsampwidth() == 1:
    sample_type = "8 Bit Integer PCM"
else:
    sample_type = "Unknown - {}".format(data.getsampwidth())

print("Format:", sample_type)
print("Number of audio samples:", data.getnframes())
print("Number of audio channels:", data.getnchannels())
print("Duration:", round(data.getnframes() / data.getframerate(), 3), "Seconds")
print("Sample rate:", data.getframerate(), "Hz")

threading.Thread(play_stream()).start()

print("Playback ended successfully.")

audio_stream.stop_stream()
audio_stream.close()
pya.terminate()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM