5

私はオーディオフレームワークを初めて使用しています。マイクからキャプチャして再生中のオーディオファイルを作成するのを手伝ってくれる人はいますか?

以下は、iPhone スピーカーを介してマイク入力を再生するコードです。今後使用するために音声を iPhone に保存したいと思います。

ここからコードを見つけて、マイクを使用してオーディオを録音しました http://www.stefanpopp.de/2011/capture-iphone-microphone/

/**

Code start from here for playing the recorded voice 

*/

static OSStatus playbackCallback(void *inRefCon, 
                                 AudioUnitRenderActionFlags *ioActionFlags, 
                                 const AudioTimeStamp *inTimeStamp, 
                                 UInt32 inBusNumber, 
                                 UInt32 inNumberFrames, 
                                 AudioBufferList *ioData) {    

    /**
     This is the reference to the object who owns the callback.
     */
    AudioProcessor *audioProcessor = (AudioProcessor*) inRefCon;

    // iterate over incoming stream an copy to output stream
    for (int i=0; i < ioData->mNumberBuffers; i++) { 
        AudioBuffer buffer = ioData->mBuffers[i];

        // find minimum size
        UInt32 size = min(buffer.mDataByteSize, [audioProcessor audioBuffer].mDataByteSize);

        // copy buffer to audio buffer which gets played after function return
        memcpy(buffer.mData, [audioProcessor audioBuffer].mData, size);

        // set data size
        buffer.mDataByteSize = size; 

         // get a pointer to the recorder struct variable
Recorder recInfo = audioProcessor.audioRecorder;
// write the bytes
OSStatus audioErr = noErr;
if (recInfo.running) {
    audioErr = AudioFileWriteBytes (recInfo.recordFile,
                                    false,
                                    recInfo.inStartingByte,
                                    &size,
                                    &buffer.mData);
    assert (audioErr == noErr);
    // increment our byte count
    recInfo.inStartingByte += (SInt64)size;// size should be number of bytes
    audioProcessor.audioRecorder = recInfo;

     }
    }

    return noErr;
}

-(void)prepareAudioFileToRecord{

NSArray *paths =             NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); // returned as a double
long digits = (long)time; // this is the first 10 digits
int decimalDigits = (int)(fmod(time, 1) * 1000); // this will get the 3 missing digits
//    long timestamp = (digits * 1000) + decimalDigits;
NSString *timeStampValue = [NSString stringWithFormat:@"%ld",digits];
//    NSString *timeStampValue = [NSString stringWithFormat:@"%ld.%d",digits ,decimalDigits];


NSString *fileName = [NSString stringWithFormat:@"test%@.caf",timeStampValue];
NSString *filePath = [basePath stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
// modify the ASBD (see EDIT: towards the end of this post!)
audioFormat.mFormatFlags = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;

// set up the file (bridge cast will differ if using ARC)
OSStatus audioErr = noErr;
audioErr = AudioFileCreateWithURL((CFURLRef)fileURL,
                                  kAudioFileCAFType,
                                  &audioFormat,
                                  kAudioFileFlags_EraseFile,
                                  &audioRecorder.recordFile);


assert (audioErr == noErr);// simple error checking
audioRecorder.inStartingByte = 0;
audioRecorder.running = true;
self.audioRecorder = audioRecorder;

}

前もってありがとうバラ

4

2 に答える 2

8

AudioBuffer からファイルにバイトをローカルに書き込むには、 AudioToolboxフレームワークに含まれているAudioFileServices リンククラスの助けが必要です。

概念的には、次のことを行います - オーディオ ファイルを設定し、それへの参照を維持します (投稿に含めた render コールバックからこの参照にアクセスできるようにする必要があります)。また、コールバックが呼び出されるたびに書き込まれるバイト数を追跡​​する必要もあります。最後に、ファイルへの書き込みを停止してファイルを閉じるように通知するフラグを確認します。

あなたが提供したリンクのコードは LPCM であり、したがって一定のビットレートであるAudioStreamBasicDescriptionを宣言しているため、 AudioFileWriteBytes関数を使用できます (圧縮オーディオの書き込みはより複雑であり、代わりに AudioFileWritePackets 関数を使用します)。

カスタム構造体 (必要なすべての追加データを含む) を宣言し、このカスタム構造体のインスタンス変数を追加して、構造体変数を指すプロパティを作成することから始めましょう。これをAudioProcessorカスタム クラスに追加します。これは、この行で型キャストしたコールバック内からこのオブジェクトに既にアクセスできるためです。

AudioProcessor *audioProcessor = (AudioProcessor*) inRefCon;

これをAudioProcessor.h (@interface の上)に追加します。

typedef struct Recorder {
AudioFileID recordFile;
SInt64 inStartingByte;
Boolean running;
} Recorder;

次に、インスタンス変数を追加し、それをポインター プロパティにして、インスタンス変数に割り当てます (コールバック関数内からアクセスできるようにします)。@interface で、 audioRecorderという名前のインスタンス変数を追加し、ASBD をクラスで使用できるようにします。

Recorder audioRecorder;
AudioStreamBasicDescription recordFormat;// assign this ivar to where the asbd is created in the class

メソッド-(void)initializeAudioで、recordFormat を ivar にしたため、この行をコメント アウトするか削除します。

//AudioStreamBasicDescription recordFormat;

ここで、ASBD が設定されている場所にkAudioFormatFlagIsBigEndianフォーマット フラグを追加します。

// also modify the ASBD in the AudioProcessor classes -(void)initializeAudio method (see EDIT: towards the end of this post!)
    recordFormat.mFormatFlags = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;

最後に、それをaudioRecorderインスタンス変数へのポインターであるプロパティとして追加し、 AudioProcessor.mで合成することを忘れないでください。ポインター プロパティにaudioRecorderPointerという名前を付けます。

@property Recorder *audioRecorderPointer;

// in .m synthesise the property
@synthesize audioRecorderPointer;

次に、ポインタを ivar に割り当てましょう (これは、 AudioProcessorクラスの-(void)initializeAudioメソッドに配置できます)。

// ASSIGN POINTER PROPERTY TO IVAR
self.audioRecorderPointer = &audioRecorder;

次に、AudioProcessor.mに、ファイルをセットアップして開くメソッドを追加して、書き込みできるようにします。これは、AUGraph の実行を開始する前に呼び出す必要があります。

-(void)prepareAudioFileToRecord {
// lets set up a test file in the documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSString *fileName = @"test_recording.aif";
    NSString *filePath = [basePath stringByAppendingPathComponent:fileName];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];

// set up the file (bridge cast will differ if using ARC)
OSStatus audioErr = noErr;
audioErr = AudioFileCreateWithURL((CFURLRef)fileURL,
                                  kAudioFileAIFFType,
                                  recordFormat,
                                  kAudioFileFlags_EraseFile,
                                  &audioRecorder.recordFile);
assert (audioErr == noErr);// simple error checking
audioRecorder.inStartingByte = 0;
audioRecorder.running = true;
}

よし、あと少しだ。これで、書き込み先のファイルと、render コールバックからアクセスできるAudioFileIDができました。したがって、投稿したコールバック関数内で、メソッドの最後で noErr を返す直前に次を追加します。

// get a pointer to the recorder struct instance variable
Recorder *recInfo = audioProcessor.audioRecorderPointer;
// write the bytes
OSStatus audioErr = noErr;
if (recInfo->running) {
audioErr = AudioFileWriteBytes (recInfo->recordFile,
                                false,
                                recInfo->inStartingByte,
                                &size,
                                buffer.mData);
assert (audioErr == noErr);
// increment our byte count
recInfo->inStartingByte += (SInt64)size;// size should be number of bytes
}

録音を停止したい場合 (おそらく何らかのユーザー アクションによって呼び出されます)、単純に実行中のブール値を false にして、AudioProcessor クラスのどこかでこのようにファイルを閉じます。

audioRecorder.running = false;
OSStatus audioErr = AudioFileClose(audioRecorder.recordFile);
assert (audioErr == noErr);

編集: サンプルのエンディアンはファイルのビッグ エンディアンである必要があるため、問題のリンクにあるソース コードの ASBD にkAudioFormatFlagIsBigEndianビット マスク フラグを追加します。

このトピックに関する追加情報については、Apple のドキュメントが優れたリソースです。また、Chris Adamson と Kevin Avila による「Learning Core Audio」を読むことをお勧めします (私はそのコピーを所有しています)。

于 2014-01-05T06:25:18.183 に答える