我试图通过使用Xcode和AudioFileServices将它们写入WAV文件来节省一些原始PCM值,但是我很难将简单的正弦波写入文件。
这是我的代码:
// Set up output file
AudioStreamBasicDescription outputFormat = {0};
outputFormat.mSampleRate = 44100;
outputFormat.mFormatID = kAudioFormatLinearPCM;
outputFormat.mBitsPerChannel = 32;
outputFormat.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked;
outputFormat.mFramesPerPacket = 1;
outputFormat.mChannelsPerFrame = 1;
outputFormat.mBytesPerFrame = 4;
outputFormat.mBytesPerPacket = 4;
AudioFileID outputFile;
CFURLRef outputFileURL =
CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("output.wav"), kCFURLPOSIXPathStyle, FALSE);
CheckError(AudioFileCreateWithURL(outputFileURL, kAudioFileWAVEType, &outputFormat, kAudioFileFlags_EraseFile, &outputFile), "Could not open output File");
CFRelease(outputFileURL);
Float32 duration = 3.0;
Float32 freq = 261.37;
Float32 amplitude = 0.3;
UInt32 sizeOfBuffer = (UInt32)(outputFormat.mSampleRate*duration)*sizeof(Float32);
Float32 *audioBuffer = (Float32*)malloc(sizeOfBuffer);
printf("Creating Buffer.... \n");
for (int i = 0; i<(int)(outputFormat.mSampleRate*duration); i++)
audioBuffer[i] = amplitude*sinf(i*freq/outputFormat.mSampleRate*2*M_PI);
printf("Writing to File.... \n");
// Write to Output File
CheckError(AudioFileWriteBytes(outputFile, FALSE, 0, &sizeOfBuffer, &audioBuffer), "Could not write bytes to file");
printf("Write Succesful!\n");
CheckError(AudioFileClose(outputFile), "Could not close file");
代码成功写入了一个正确的持续时间的文件,但听起来确实是扭曲的。我错过了什么吗?
答案 0 :(得分:2)
回答了我自己的问题。当我使用AudioFileWriteBytes
时,我应该传递&audioBuffer
,因为它已经是指针。
这是正确的代码:
audioBuffer