我使用以下方法从文本文件生成频率声音序列:
import mmap
import math
import pyaudio
fh = open('/home/jay/Documents/try.txt', 'rb')
m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
ba = bytearray(m)
#sudo apt-get install python-pyaudio
PyAudio = pyaudio.PyAudio
#See http://en.wikipedia.org/wiki/Bit_rate#Audio
BITRATE = 16000 #number of frames per second/frameset.
for freq in ba:
#See http://www.phy.mtu.edu/~suits/notefreqs.html
FREQUENCY = 300 + freq #Hz, waves per second, 261.63=C4-note.
LENGTH = 1 #seconds to play sound
NUMBEROFFRAMES = int(BITRATE * LENGTH)
RESTFRAMES = NUMBEROFFRAMES % BITRATE
WAVEDATA = ''
for x in xrange(NUMBEROFFRAMES):
WAVEDATA = WAVEDATA+chr(int(math.sin(x/((BITRATE/FREQUENCY)/math.pi))*127+128))
#fill remainder of frameset with silence
for x in xrange(RESTFRAMES):
WAVEDATA = WAVEDATA+chr(128)
p = PyAudio()
stream = p.open(format = p.get_format_from_width(1),
channels = 1,
rate = BITRATE,
output = True)
stream.write(WAVEDATA)
stream.stop_stream()
stream.close()
p.terminate()
(try.txt
可以是您想要的任何文本文件)
但它在频率声音之间有一些噪音如何删除它并保存在.wave或.mp3文件中播放的所有频率的序列? 对不起我还在学习,如果我不清楚要求。 谢谢, 杰
答案 0 :(得分:0)
这里最大的问题是你在每个频率打开/关闭音频流。
相反,请保持流畅通,您将获得更少的点击次数"。这并不意味着您没有获得任何点击,可能是因为处理时间有时太长而且流被中断。最好的方法是多线程生成和写入更具反应性,但这是另一个故事......
我还添加了.wav
个保存容量。我的输出文件名。效果很好。
固定代码(使用Python 3运行)
import mmap
import math
import pyaudio,wave
import array
fh = open('K:\out.txt', 'rb')
m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
ba = bytearray(m)
#ba = [300,400,500,400,200]
#sudo apt-get install python-pyaudio
PyAudio = pyaudio.PyAudio
#See http://en.wikipedia.org/wiki/Bit_rate#Audio
BITRATE = 16000 #number of frames per second/frameset.
p = PyAudio()
stream = p.open(format = p.get_format_from_width(1),
channels = 1,
rate = BITRATE,
output = True)
wf=wave.open("K:\wavout.wav","wb")
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt8)) # byte = 8 bits else trashed
wf.setframerate(BITRATE)
for freq in ba:
#See http://www.phy.mtu.edu/~suits/notefreqs.html
FREQUENCY = 300 + freq #Hz, waves per second, 261.63=C4-note.
print('freq '+str(FREQUENCY))
LENGTH = 1 #seconds to play sound
NUMBEROFFRAMES = int(BITRATE * LENGTH)
RESTFRAMES = NUMBEROFFRAMES % BITRATE
WAVEDATA = list()
for x in range(NUMBEROFFRAMES):
v = int(math.sin(x/((BITRATE/FREQUENCY)/math.pi))*127+128)
WAVEDATA.append(v)
#fill remainder of frameset with silence
WAVEDATA+=[128]*RESTFRAMES
b = array.array('B', WAVEDATA).tostring()
wf.writeframes(b)
stream.write(b)
#print data
wf.close()
stream.stop_stream()
stream.close()
p.terminate()