Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Created Jun 22, 2012
Embed
What would you like to do?
Mac / 標準入力を再生するやつ (適当)
#include <iostream>
#import <AudioUnit/AudioUnit.h>
using namespace std;
static bool finished = false;
static OSStatus AudioUnitCallback
(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber,
UInt32 inNumberFrames, AudioBufferList *ioData)
{
static int err = 0;
float samples[inNumberFrames];
for (uint i = 0; i < inNumberFrames; i++) {
REDO:
cin >> samples[i];
if (cin.fail()) {
if (++err > 1024) {
finished = true;
break;
}
cin.clear();
goto REDO;
} else {
err = 0;
}
}
if (finished) {
for (uint i = 0; i < inNumberFrames; i++) samples[i] = 0.0f;
}
for (uint ch = 0; ch < 2; ch++) {
AudioUnitSampleType *out = (AudioUnitSampleType*)ioData->mBuffers[ch].mData;
for (uint i = 0; i < inNumberFrames; i++) {
*out++ = samples[i] * 0.5;
}
}
return noErr;
}
int main(int argc, void *argv[]) {
AudioUnit audioUnit;
AudioComponentDescription cd;
cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_DefaultOutput;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;
cd.componentFlags = 0;
cd.componentFlagsMask = 0;
AudioComponent component = AudioComponentFindNext(NULL, &cd);
AudioComponentInstanceNew(component, &audioUnit);
AudioUnitInitialize(audioUnit);
uint sampleRate;
{
Float64 _sampleRate;
UInt32 size = sizeof(Float64);
AudioUnitGetProperty(audioUnit,
kAudioUnitProperty_SampleRate,
kAudioUnitScope_Output,
0,
&_sampleRate,
&size);
sampleRate = (uint)_sampleRate;
}
cout << "samplerate: " << sampleRate << endl;
uint channels = 2;
AURenderCallbackStruct callback;
callback.inputProc = AudioUnitCallback;
AudioUnitSetProperty(audioUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input,
0,
&callback,
sizeof(AURenderCallbackStruct));
AudioStreamBasicDescription audioFormat;
audioFormat.mSampleRate = sampleRate;
audioFormat.mFormatID = kAudioFormatLinearPCM;
audioFormat.mFormatFlags = kAudioFormatFlagsAudioUnitCanonical;
audioFormat.mChannelsPerFrame = channels;
audioFormat.mBytesPerPacket = sizeof(AudioUnitSampleType);
audioFormat.mBytesPerFrame = sizeof(AudioUnitSampleType);
audioFormat.mFramesPerPacket = 1;
audioFormat.mBitsPerChannel = 8 * sizeof(AudioUnitSampleType);
audioFormat.mReserved = 0;
AudioUnitSetProperty(audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&audioFormat,
sizeof(audioFormat));
AudioOutputUnitStart(audioUnit);
while (!finished);
AudioOutputUnitStop(audioUnit);
return 0;
}
use strict;
use warnings;
my $phase = 0;
while (1) {
print sin(6.28 * $phase);
$phase += 880 / 48000;
}
% g++ -o cin2audio cin2audio.cpp -framework AudioUnit
% perl sound.pl | ./cin2audio
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment