使用Core Audio生成方波

时间:2013-09-22 12:55:15

标签: core-audio wave

我正在尝试使用Core Audio生成方波,并使用以下代码。无论我传递任何参数,AIFF文件都不会生成任何内容。样本来自Kevin Avila的学习核心音频http://www.amazon.com/Learning-Core-Audio-Hands-On-Programming/dp/0321636848

任何想法?请帮忙!

main.m如下所示;

#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#define SAMPLE_RATE 44100
#define DURATION 50.0
#define FILENAME_FORMAT @"%0.3f-square.aif"
int main (int argc, const char * argv[]) {
@autoreleasepool {
    if (argc < 2) {
        printf ("Usage: CAToneFileGenerator n\n(where n is tone in Hz)");
        return -1;
        }
    double hz = atof(argv[1]);
    assert (hz > 0);
    NSLog (@"generating %f hz tone", hz);
    NSString *fileName = [NSString stringWithFormat: FILENAME_FORMAT, hz];
    NSString *filePath = [[[NSFileManager defaultManager] currentDirectoryPath]
                          stringByAppendingPathComponent: fileName]; NSURL *fileURL = [NSURL fileURLWithPath: filePath];
    // Prepare the format
    AudioStreamBasicDescription asbd;
    memset(&asbd, 0, sizeof(asbd));
    asbd.mSampleRate = SAMPLE_RATE;
    asbd.mFormatID = kAudioFormatLinearPCM;
    asbd.mFormatFlags = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
    asbd.mBitsPerChannel = 16;
    asbd.mChannelsPerFrame = 1;
    asbd.mFramesPerPacket = 1;
    asbd.mBytesPerFrame = 2; asbd.mBytesPerPacket = 2;
    // Set up the file
    AudioFileID audioFile;
    OSStatus audioErr = noErr;
    audioErr = AudioFileCreateWithURL((__bridge CFURLRef)fileURL,
                                      kAudioFileAIFFType,
                                      &asbd,
                                      kAudioFileFlags_EraseFile,
                                      &audioFile);
    assert (audioErr == noErr);
    // Start writing samples
    long maxSampleCount = SAMPLE_RATE;
    long sampleCount = 0;
    UInt32 bytesToWrite = 2;
    double wavelengthInSamples = SAMPLE_RATE / hz;
    while (sampleCount < maxSampleCount) {
        for (int i=0; i<wavelengthInSamples; i++) {
            // Square wave
            SInt16 sample;
            if (i < wavelengthInSamples/2) {
                sample = CFSwapInt16HostToBig (SHRT_MAX); } else {
                    sample = CFSwapInt16HostToBig (SHRT_MIN); }
            audioErr = AudioFileWriteBytes(audioFile, false,
                                           sampleCount*2, &bytesToWrite, &sample);
            assert (audioErr == noErr); sampleCount++;
            audioErr = AudioFileClose(audioFile); assert (audioErr == noErr);
            NSLog (@"wrote %ld samples", sampleCount);
        }
        return 0;
    }
}

}

1 个答案:

答案 0 :(得分:1)

非常确定你的AudioFileClose()不应该在for循环中。在你写完所有样本之后,这应该在循环之外。

请检查the book's home page处的可下载代码。我刚刚下载并运行它,它的工作原理如书中所述(尽管,因为它是为Lion构建的,所以如果您使用的是Mountain Lion或Mavericks,则必须在项目设置中更新目标SDK)

- Chris(无效名称)