转换后无法访问音频文件

时间:2011-09-11 08:42:24

标签: iphone objective-c avfoundation avaudioplayer

我一直在使用以下代码将aac / mp3文件转换为pcm。代码工作正常。但是,如果我尝试播放该文件或使用AVAudioPlayer对其执行任何操作,那么在转换完成之后,没有任何事情发生,就好像文件不在那里一样。它没有给我任何错误,如果我重新启动应用程序然后它的工作原理。我花了我们的努力来解决这个问题,但我没有任何线索。谢谢你的帮助

// open an ExtAudioFile
ExtAudioFileRef inputFile;
ExtAudioFileOpenURL((CFURLRef)exportURL, &inputFile);

// prepare to convert to a plain ol' PCM format
AudioStreamBasicDescription myPCMFormat;
myPCMFormat.mSampleRate = 22050.0;
myPCMFormat.mFormatID = kAudioFormatLinearPCM ;
myPCMFormat.mFormatFlags =  kAudioFormatFlagsCanonical;
myPCMFormat.mChannelsPerFrame = 2;
myPCMFormat.mFramesPerPacket = 1;
myPCMFormat.mBitsPerChannel = 16;
myPCMFormat.mBytesPerPacket = 4;
myPCMFormat.mBytesPerFrame = 4;

ExtAudioFileSetProperty(inputFile, kExtAudioFileProperty_ClientDataFormat, sizeof (myPCMFormat), &myPCMFormat);

// allocate a big buffer. size can be arbitrary for ExtAudioFile.
// you have 64 KB to spare, right?
UInt32 outputBufferSize = 0x10000;
void* ioBuf = malloc (outputBufferSize);
UInt32 sizePerPacket = myPCMFormat.mBytesPerPacket;
UInt32 packetsPerBuffer = outputBufferSize / sizePerPacket;

// set up output file
NSString *outputPath = [[self pathOfFile2] stringByAppendingPathComponent: AS(final, @".aiff")];
NSURL *outputURL = [NSURL fileURLWithPath:outputPath];
AudioFileID outputFile;
AudioFileCreateWithURL((CFURLRef)outputURL,
                                   kAudioFileCAFType,
                                   &myPCMFormat,
                                   kAudioFileFlags_EraseFile,
                                   &outputFile);

// start convertin'
UInt32 outputFilePacketPosition = 0; //in bytes

while (true) {
    // wrap the destination buffer in an AudioBufferList
    AudioBufferList convertedData;
    convertedData.mNumberBuffers = 1;
    convertedData.mBuffers[0].mNumberChannels = myPCMFormat.mChannelsPerFrame;
    convertedData.mBuffers[0].mDataByteSize = outputBufferSize;
    convertedData.mBuffers[0].mData = ioBuf;

    UInt32 frameCount = packetsPerBuffer;

    // read from the extaudiofile
    ExtAudioFileRead(inputFile, &frameCount, &convertedData);

    if (frameCount == 0) {
        break;
    }

    // write the converted data to the output file
    AudioFileWritePackets(outputFile,
                                       false,
                                       frameCount,
                                       NULL,
                                       outputFilePacketPosition / myPCMFormat.mBytesPerPacket,
                                       &frameCount,
                                       convertedData.mBuffers[0].mData);

    // advance the output file write location
    outputFilePacketPosition +=
    (frameCount * myPCMFormat.mBytesPerPacket);
}

// clean up
ExtAudioFileDispose(inputFile);
AudioFileClose(outputFile);

1 个答案:

答案 0 :(得分:1)

听起来文件上有锁。您可能需要将FileID放在AudioFileClose行中......

AudioFileID fileID;
AudioFileClose(fileID);