新聞中心
在Python中錄音,我們可以使用pyaudio庫(kù)。pyaudio是一個(gè)用于錄制和播放音頻的Python庫(kù),它是基于PortAudio的跨平臺(tái)庫(kù),PortAudio是一個(gè)用于音頻I/O的跨平臺(tái)庫(kù),支持多種操作系統(tǒng),如Windows、macOS和Linux。

以下是一個(gè)簡(jiǎn)單的錄音示例:
1、確保已經(jīng)安裝了pyaudio庫(kù),如果沒(méi)有安裝,可以使用以下命令進(jìn)行安裝:
pip install pyaudio
2、創(chuàng)建一個(gè)名為record_audio.py的Python文件,并添加以下代碼:
import pyaudio
import wave
import sys
def record_audio(filename, duration, channels=1, rate=44100, chunk=1024):
audio_format = pyaudio.paInt16
p = pyaudio.PyAudio()
stream = p.open(format=audio_format,
channels=channels,
rate=rate,
input=True,
frames_per_buffer=chunk)
print("開(kāi)始錄音,請(qǐng)說(shuō)話...")
frames = []
for i in range(0, int(rate / chunk * duration)):
data = stream.read(chunk)
frames.append(data)
print("錄音結(jié)束,正在保存...")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(audio_format))
wf.setframerate(rate)
wf.writeframes(b''.join(frames))
wf.close()
if __name__ == "__main__":
if len(sys.argv) < 4:
print("用法: python record_audio.py <輸出文件名> <錄音時(shí)長(zhǎng)(秒)> [聲道數(shù)] [采樣率] [每次讀取的幀數(shù)]")
sys.exit(1)
filename = sys.argv[1]
duration = float(sys.argv[2])
channels = int(sys.argv[3]) if len(sys.argv) >= 4 else 1
rate = int(sys.argv[4]) if len(sys.argv) >= 5 else 44100
chunk = int(sys.argv[5]) if len(sys.argv) >= 6 else 1024
record_audio(filename, duration, channels, rate, chunk)
3、運(yùn)行record_audio.py文件,指定輸出文件名、錄音時(shí)長(zhǎng)、聲道數(shù)、采樣率和每次讀取的幀數(shù)。
python record_audio.py output.wav 5 1 44100 1024
這將錄制5秒鐘的音頻,并將其保存為output.wav文件,注意,錄音時(shí)需要保持麥克風(fēng)打開(kāi)并說(shuō)話,錄音結(jié)束后,音頻將被保存到指定的文件中。
注意:在某些操作系統(tǒng)上,可能需要安裝PortAudio庫(kù)才能正常使用pyaudio,在macOS上,可以使用以下命令安裝PortAudio:
brew install portaudio withlibsndfile withavutil withflac withlibvorbis withlibogg withopus withsdl2 withportmidi withportsmf withportmixer withpulseaudio withalsa withjack withjpeg withlibshine withrtmpdump withlibtheora withlibvorbisenc withlibmp3lame withlibopencoreamrnb withlibopencoreamrwb withva withvideotoolbox withlibvoaacenc withfrei0r withlibtwolame withlibfdkaac withffmpeg withlibcaca withx264 withopenssl withoutnasm withoutdoxygen withoutgraphviz withoutqt withoutgtktest withoutexamples withouttests HEAD vd skipinstalled formula && brew link portaudio && sudo port v selfupdate && sudo port v install py27pyaudio || true
以上就是在Python中錄音的方法,希望對(duì)您有所幫助!
文章題目:python中如何錄音
文章出自:http://www.dlmjj.cn/article/coogsgs.html


咨詢
建站咨詢
