使用 PyAudio 在 Python 中列出所有連線到系統的麥克風


介紹

使用音訊資料的 Python 程式設計師可以使用靈活的 PyAudio 包。它提供 PortAudio Python 繫結,這是一個多平臺音訊輸入/輸出 (I/O) 工具包,使 Python 程式能夠在多個平臺上播放和錄製音訊。在本文中,我們將瞭解如何使用 PyAudio 列出所有連線到系統的麥克風。這是一個在處理音訊資料時特別有用的功能。

PyAudio 安裝

在繼續示例之前,讓我們首先確保 PyAudio 已安裝在您的系統上。Python 的包安裝程式 pip 使這個過程很簡單。開啟終端後,執行以下命令:

pip install pyaudio

在命令前使用感嘆號可以在 Jupyter notebook 中執行它:

!pip install pyaudio

PyAudio 基礎知識和識別麥克風

首先,您必須建立一個 PyAudio 例項才能與系統的音訊功能進行互動。擁有一個例項後,就可以使用 PyAudio 的所有方法。在這種情況下,`get_device_info_by_index` 和 `get_device_count` 函式特別重要。

import pyaudio

# Create an instance of PyAudio
p = pyaudio.PyAudio()

# Get the number of audio I/O devices
devices = p.get_device_count()

# Print the total number of devices
print(f'Total number of devices: {devices}')

此指令碼將列印連線到系統的音訊輸入/輸出裝置的總數。

為了編譯所有麥克風的列表,我們必須反覆遍歷所有裝置並確定它們是否是輸入裝置(麥克風)。裝置的“maxInputChannels”屬性有助於確定它是否是麥克風。

import pyaudio

# Create an instance of PyAudio
p = pyaudio.PyAudio()

# Get the number of audio I/O devices
devices = p.get_device_count()

# Iterate through all devices
for i in range(devices):
   # Get the device info
   device_info = p.get_device_info_by_index(i)
   # Check if this device is a microphone (an input device)
   if device_info.get('maxInputChannels') > 0:
      print(f"Microphone: {device_info.get('name')} , Device Index: {device_info.get('index')}")

高階用法:選擇麥克風

讓我們使我們的指令碼更加複雜。考慮選擇一個麥克風來捕捉音訊。為此,我們可以使用裝置的“index”屬性。這是一個關於如何操作的示例

import pyaudio

# Create an instance of PyAudio
p = pyaudio.PyAudio()

def select_microphone(index):
   # Get the device info
   device_info = p.get_device_info_by_index(index)
   # Check if this device is a microphone (an input device)
   if device_info.get('maxInputChannels') > 0:
      print(f"Selected Microphone: {device_info.get('name')}")
   else:
      print(f"No microphone at index {index}")

# Select a microphone with a specific index
select_microphone(1)

結論

您可以使用 PyAudio(一個強大的 Python 音訊資料處理工具包)輕鬆管理和修改連線的麥克風,使您可以建立複雜的音訊處理應用程式。

我們已經看到的示例演示瞭如何從連線到系統的麥克風列表中選擇特定麥克風。藉助這些基礎知識,您可以開發您的基於音訊的應用程式,以包含更高階的功能,例如即時音訊錄製、分析和處理。

更新於:2023年7月18日

2K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.