从内置麦克风获取音频信号

时间:2018-02-13 11:20:26

标签: python-3.x audio signals

我想将音频信号发送给Pycharm,以便我可以试验一下,看看我能用它做什么。

我可以输入一个特定的功能来从我正在使用的设备中检索原始音频信号吗?

1 个答案:

答案 0 :(得分:0)

这应该是你的开始...它是一些记录麦克风音频并将其停放到输出wav文件的python

import pyaudio
import wave
# import urllib.request
import urllib
import struct
import numpy as np
import sounddevice as sd
import matplotlib.pyplot as plt

# Callback function---------------------------------
def callback(indata, outdata, frames, time, status):
#    if status:
#        print(status)
    outdata[:] = indata
#---------------------------------------------------

# Parameters ----------------------------------------------
# Window_Size = 22050 # Point
# Window_Size = 1024 # Point
Window_Size = 2048 # Point
FORMAT_D = pyaudio.paFloat32; FORMAT_W = pyaudio.paInt32
CHANNELS = 1 # Mono
Sample_Rate = 22050 # Hz
dT = 1/Sample_Rate
RECORD_SECONDS = 20 # s
NOFFRAMES = int(Sample_Rate/Window_Size * RECORD_SECONDS)
WAVE_OUTPUT_FILENAME = "/tmp/python_audio_output.wav"
#-----------------------------------------------------------

p = pyaudio.PyAudio()

stream_D = p.open(format=FORMAT_D,
                channels=CHANNELS,
                rate=Sample_Rate,
                input=True,
                frames_per_buffer=Window_Size)

stream_W = p.open(format=FORMAT_W,
            channels=CHANNELS,
            rate=Sample_Rate,
            input=True,
            frames_per_buffer=Window_Size)

print("* recording")

frames = []


for i in range(0, int(Sample_Rate/Window_Size * RECORD_SECONDS)):
    data_D = stream_D.read(Window_Size)
#    data_W = stream_W.read(Window_Size)
    decoded = np.fromstring(data_D, 'Float32')
#    np.savetxt(str(i)+'ttt.txt',transform)
    sd.play(decoded,22050)
#    frames.append(data_W)
#-------------------------------------------------------

print("* done recording")

stream_D.stop_stream()
stream_D.close()
p.terminate()

#plt.plot(transform)
#plt.show()

# Save as a wave file---------------------------
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT_W))
wf.setframerate(Sample_Rate)
wf.writeframes(b''.join(frames))
wf.close()
#-------------------------------------------