You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi 11 FMX如何获取默认音频输出设备?是否遗漏相关方法?

获取Delphi 11 FMX默认音频输出设备的简化方案

FMX.Media单元确实没有提供类似DefaultAudioCaptureDevice/DefaultVideoCaptureDevice的统一属性来直接获取默认音频输出设备,需要针对Windows和Mac平台分别实现,但可以封装成跨平台的简化函数,避免重复编写繁琐代码。

跨平台封装实现

以下是封装后的简化代码,可直接调用获取默认音频输出设备的UniqueID:

uses
  System.SysUtils, FMX.Types;

{$IFDEF MSWINDOWS}
uses
  Winapi.Windows, Winapi.MMSystem, Winapi.MMDeviceApi, Winapi.ActiveX;
{$ENDIF}

{$IFDEF MACOS}
uses
  Macapi.CoreFoundation, Macapi.AVFoundation, Macapi.ObjectiveC;
{$ENDIF}

function GetDefaultAudioOutputDeviceID: string;
{$IFDEF MSWINDOWS}
var
  LDeviceEnumerator: IMMDeviceEnumerator;
  LDefaultDevice: IMMDevice;
  LDeviceID: PWideChar;
begin
  Result := '';
  if CoCreateInstance(CLSID_MMDeviceEnumerator, nil, CLSCTX_ALL, IID_IMMDeviceEnumerator, LDeviceEnumerator) = S_OK then
  begin
    if LDeviceEnumerator.GetDefaultAudioEndpoint(eRender, eConsole, LDefaultDevice) = S_OK then
    begin
      if LDefaultDevice.GetId(LDeviceID) = S_OK then
      begin
        Result := LDeviceID;
        CoTaskMemFree(LDeviceID);
      end;
    end;
  end;
end;
{$ENDIF}

{$IFDEF MACOS}
var
  LSession: AVAudioSession;
  LOutputDeviceID: AudioDeviceID;
  LCFString: CFStringRef;
begin
  Result := '';
  LSession := TAVAudioSession.Wrap(TAVAudioSession.OCClass.sharedInstance);
  if LSession.currentRoute.outputs.count > 0 then
  begin
    LOutputDeviceID := LSession.currentRoute.outputs.objectAtIndex(0).deviceID;
    // 获取设备唯一UID
    LCFString := AudioHardwareGetPropertyString(kAudioHardwarePropertyDeviceUID, LOutputDeviceID);
    if Assigned(LCFString) then
    begin
      Result := CFStringToStr(LCFString);
      CFRelease(LCFString);
    end;
  end;
end;
{$ENDIF}

使用方式

调用时只需一行代码,和获取捕获设备的逻辑一致:

var
  LOutputDeviceID: string;
begin
  LOutputDeviceID := GetDefaultAudioOutputDeviceID;
  if not LOutputDeviceID.IsEmpty then
  begin
    // 处理设备ID
  end;
end;

说明:

  • Windows平台通过MMDeviceAPI的IMMDeviceEnumerator接口获取默认渲染设备(音频输出)
  • Mac平台通过AVAudioSession获取当前路由的默认输出设备,代码中获取的是设备唯一UID,若需设备名称可改用kAudioHardwarePropertyDeviceName

内容的提问来源于stack exchange,提问作者Haifisch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:43:23