核心音频HALOutput音频单元无法调用输入回调

时间:2018-07-06 03:32:24

标签: rust core-audio

我正在尝试在Mac上使用Core Audio录制音频,但是没有调用我的输入回调。我确定我缺少明显的东西,但是我整天都在搜索和尝试一些东西。我的代码是用Rust编写的,但希望对于C / C ++的人来说,遵循它不会太难。在这里:

extern crate coreaudio_sys;
#[macro_use]
extern crate objc;

use std::mem::size_of_val;
use std::os::raw::c_void;
use std::ptr;

use coreaudio_sys::*;
use objc::runtime::{Object, Class};

#[link(name = "Foundation", kind = "framework")] 
extern {}

fn main() {
    unsafe {
        // First, create an audio unit.
        let desc = AudioComponentDescription {
            componentType: kAudioUnitType_Output,
            componentSubType: kAudioUnitSubType_HALOutput,
            componentManufacturer: kAudioUnitManufacturer_Apple,
            ..AudioComponentDescription::default()
        };

        let mut au_hal: AudioComponentInstance = ptr::null_mut();
        let comp = AudioComponentFindNext(ptr::null_mut(), &desc);
        assert_ne!(comp, ptr::null_mut());

        let mut code: OSStatus;

        code = AudioComponentInstanceNew(comp, &mut au_hal);
        assert_eq!(code, 0);

        // Next, enable IO for input.
        let enable_io: UInt32 = 1;
        code = AudioUnitSetProperty(
            au_hal,
            kAudioOutputUnitProperty_EnableIO,
            kAudioUnitScope_Input,
            1,
            &enable_io as *const _ as *const _,
            size_of_val(&enable_io) as u32,
        );
        assert_eq!(code, 0);

        // Set the input callback.
        let input = AURenderCallbackStruct {
            inputProc: Some(input_proc),
            inputProcRefCon: ptr::null_mut(),
        };
        code = AudioUnitSetProperty(
            au_hal,
            kAudioOutputUnitProperty_SetInputCallback,
            kAudioUnitScope_Global,
            1,
            &input as *const _ as *const _,
            size_of_val(&input) as u32,
        );
        assert_eq!(code, 0);

        // Finally, initialize and start the unit.
        code = AudioUnitInitialize(au_hal);
        assert_eq!(code, 0);

        code = AudioOutputUnitStart(au_hal);
        assert_eq!(code, 0);

        // Edit: As per Rhythmic Fistman's answer, use an
        // NSRunLoop instead of a "loop {}".
        // This code translates to [[NSRunLoop mainRunLoop] run]; in ObjC.
        //
        // This did not solve my problem.
        let NSRunLoop = Class::get("NSRunLoop").unwrap();
        let run_loop: *mut Object = msg_send![NSRunLoop, mainRunLoop];
        msg_send![run_loop, run];
    }
}

出于调试目的,我的input_proc回调仅在打印“ hi input”后返回0:

unsafe extern "C" fn input_proc(
    in_ref_con: *mut c_void,
    io_action_flags: *mut AudioUnitRenderActionFlags,
    in_time_stamp: *const AudioTimeStamp,
    in_bus_number: UInt32,
    in_number_frames: UInt32,
    io_data: *mut AudioBufferList,
) -> OSStatus {
    println!("hi input");
    0
}

因此,我希望看到“ hi input”被重复打印到控制台。实际上,什么都没打印出来。

1 个答案:

答案 0 :(得分:2)

在Mac上,您需要告诉AudioUnit使用哪个音频设备。就我而言,我不得不禁用本机上的扬声器输出-可能是因为Mac上的默认输入设备仅能输入。

在C语言中(我认为Rust版本将需要几个as *const _ as *const _as u32 s):

// disable output (needed, otherwise I can't set device)
flag = 0;
err = AudioUnitSetProperty(au, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &flag, sizeof(flag));
assert(noErr == err);

// get default input device
AudioObjectPropertyAddress propAddr = {
    .mSelector = kAudioHardwarePropertyDefaultInputDevice,
    .mScope = kAudioObjectPropertyScopeGlobal,
    .mElement = kAudioObjectPropertyElementMaster
};

AudioDeviceID deviceID;
UInt32 propertySize = sizeof(deviceID);
err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propAddr, 0, NULL, &propertySize, &deviceID);
assert(noErr == err);

// set audio unit current device
err = AudioUnitSetProperty(au, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceID, sizeof(deviceID));
assert(noErr == err);

全部:

static OSStatus
AUInputCallback(
    void*                       inRefCon,
    AudioUnitRenderActionFlags* ioActionFlags,
    const AudioTimeStamp*       inTimeStamp,
    UInt32                      inBusNumber,
    UInt32                      inNumberFrames,
    AudioBufferList*            ioData)
{
    printf("poot\n");
    return noErr;
}

int
main(int argc, char **argv) {
    AudioComponentDescription desc = {
        .componentType = kAudioUnitType_Output,
        .componentSubType = kAudioUnitSubType_HALOutput,
        .componentManufacturer = kAudioUnitManufacturer_Apple,
        .componentFlags = 0,
        .componentFlagsMask = 0
    };

    AudioComponent comp = AudioComponentFindNext(NULL, &desc);
    assert(comp);

    AudioUnit au;
    OSStatus err = AudioComponentInstanceNew(comp, &au);
    assert(noErr == err);

    // enable input
    UInt32      flag = 1;
    err = AudioUnitSetProperty(au, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &flag, sizeof(flag));
    assert(noErr == err);

    // disable output (needed, otherwise I can't set device)
    flag = 0;
    err = AudioUnitSetProperty(au, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &flag, sizeof(flag));
    assert(noErr == err);

    AURenderCallbackStruct cb;
    cb.inputProc = AUInputCallback;
    cb.inputProcRefCon = NULL;
    err = AudioUnitSetProperty(au, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 1, &cb, sizeof(cb));
    assert(noErr == err);

    // set audio unit device to default input device
    AudioObjectPropertyAddress propAddr = {
        .mSelector = kAudioHardwarePropertyDefaultInputDevice,
        .mScope = kAudioObjectPropertyScopeGlobal,
        .mElement = kAudioObjectPropertyElementMaster
    };

    AudioDeviceID deviceID;
    UInt32 propertySize = sizeof(deviceID);
    err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propAddr, 0, NULL, &propertySize, &deviceID);
    assert(noErr == err);

    err = AudioUnitSetProperty(au, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceID, sizeof(deviceID));
    assert(noErr == err);

    err = AudioUnitInitialize(au);
    assert(noErr == err);

    err = AudioOutputUnitStart(au);
    assert(noErr == err);

    while (1) {}

    return 0;
}