【问题标题】:How do I store the sound generated in this pyaudio stream into a WAV or MP3 file?如何将此 pyaudio 流中生成的声音存储到 WAV 或 MP3 文件中?
【发布时间】:2015-12-14 23:14:12
【问题描述】:
"""Play a fixed frequency sound."""
from __future__ import division
import math
from pyaudio import PyAudio

def sine_tone(frequency, duration, volume=1, sample_rate=22050):
    n_samples = int(sample_rate * duration)
    restframes = n_samples % sample_rate

    p = PyAudio()
    stream = p.open(format=p.get_format_from_width(1), # 8bit
                    channels=1, # mono
                    rate=sample_rate,
                    output=True)
    s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate)
    samples = (int(s(t) * 0x7f + 0x80) for t in range(n_samples))
    for buf in zip(*[samples]*sample_rate): # write several samples at a time
        stream.write(bytes(bytearray(buf)))

    # fill remainder of frameset with silence
    stream.write(b'\x80' * restframes)

    stream.stop_stream()
    stream.close()
    p.terminate()


def playScale(scale):
    for x in scale:
        print(x)
        sine_tone(frequency = x,
                  duration = 1,
                  volume=.5,
                  sample_rate = 50000)

playScale 函数接受一个频率数组并使用 sine_tone 函数播放它们。如何将这一系列声音保存到 .WAV 文件或 .MP3 文件中?

【问题讨论】:

    标签: python python-3.x python-3.2 pyaudio


    【解决方案1】:

    您应该将所有音频数据写入一个流,然后您可以使用 python 中的“wave”库保存该流,该库可以处理波形文件。

    但是,对于您当前的代码,我不确定它会如何工作,因为您正在为每个声音/音调编写单独的流。可能希望将流传递给该函数,以便您也可以附加该流并稍后在呈现所有音频时使用不同的函数保存。

    https://docs.python.org/2/library/wave.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      相关资源
      最近更新 更多