使用预订示例代码学习核心音频不起作用

时间:2013-09-13 21:22:46

标签: core-audio command-line-tool

您好我正在尝试学习本书的核心音频农场:http://www.amazon.com/Learning-Core-Audio-Hands-On-Programming/dp/0321636848

但是当我尝试运行此代码时:

      #import <Foundation/Foundation.h>
     #import <AudioToolbox/AudioToolbox.h>

#define SAMPLE_RATE 44100
 #define DURATION 5
  #define FILENAME_FORMAT @"%0.03f-test.aif"

  int main(int argc, const char * argv[])
 {

@autoreleasepool
{
    if(argc<2)
        return -1;

    double hz = 44;
    assert(hz>0);
    NSLog(@"Generating hz tone:%f",hz);

    NSString* fileName = [NSString stringWithFormat:FILENAME_FORMAT, hz];
    NSString* filePath = [[[NSFileManager defaultManager]currentDirectoryPath]
                          stringByAppendingPathComponent:fileName];
    NSURL* fileURL = [NSURL fileURLWithPath:filePath];


    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;


    AudioFileID audioFile;
    OSStatus audioErr = noErr;
    audioErr = AudioFileCreateWithURL((__bridge CFURLRef)fileURL, kAudioFileAIFFType, &asbd, kAudioFileFlags_EraseFile, &audioFile);
    assert(audioErr == noErr);

    long maxSampleCount = SAMPLE_RATE * DURATION;
    long sampleCount = 0;
    UInt32 bytesToWrite = 2;
    double waveLengthInSamples = SAMPLE_RATE / hz;

    while(sampleCount < maxSampleCount)
    {
        for(int i=0;i<waveLengthInSamples;i++)
        {
            SInt16 sample;
            if(i<waveLengthInSamples/2)
                sample = CFSwapInt16BigToHost(SHRT_MAX);
            else
                sample = CFSwapInt16BigToHost(SHRT_MIN);

            audioErr = AudioFileWriteBytes(audioFile, false, sampleCount*2, &bytesToWrite, &sample);
            assert(audioErr = noErr);
            sampleCount++;
        }
    }

    audioErr = AudioFileClose(audioFile);
    assert(audioErr = noErr);


}
return 0;

}

带有此错误代码的程序退出:程序以退出代码结束:255

任何人都可以帮助我吗?我下载了示例代码,发生了同样的错误。我正在使用xcode 5和64位macbook。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

看起来你修改了本书的代码,明确地将音调设置为44Hz。

double hz = 44;

但是,原始代码希望您输入音调作为命令行参数。这些行正在检查该参数,并在没有找到参数时返回-1(或255)。

if(argc<2)
    return -1;

删除这两行以删除参数检查。