2015-12-14 128 views
2
"""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文件?如何将此pyaudio流中生成的声音存储到WAV或MP3文件中?

回答

0

你应该把所有的音频数据写入一个流,然后你可以使用Python中的'wave'库来保存这个流,这个库可以处理波形文件。

但是,使用您当前的代码,我不确定它是如何工作的,因为您正在为每个声音/音调编写单独的流。可能想将一个流传递给该函数,以便在渲染完所有音频后,您可以将该流附加到该流中并稍后使用其他函数进行保存。

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

相关问题