iOS audio manipulation - play local .caf file backwards

后端 未结 5 1766
遇见更好的自我
遇见更好的自我 2021-01-14 12:55

I\'m wanting to load a local .caf audio file and reverse the audio (play it backwards). I\'ve gathered that I basically need to flip an array of buffer data from posts like

5条回答
  •  抹茶落季
    2021-01-14 13:17

    I have worked on a sample app, which records what user says and plays them backwards. I have used CoreAudio to achieve this. Link to app code.

    As each sample is 16-bits in size(2 bytes)(mono channel). You can load each sample at a time by copying it into a different buffer by starting at the end of the recording and reading backwards. When you get to the start of the data you have reversed the data and playing will be reversed.

    // set up output file
    AudioFileID outputAudioFile;
    
    AudioStreamBasicDescription myPCMFormat;
    myPCMFormat.mSampleRate = 16000.00;
    myPCMFormat.mFormatID = kAudioFormatLinearPCM ;
    myPCMFormat.mFormatFlags =  kAudioFormatFlagsCanonical; 
    myPCMFormat.mChannelsPerFrame = 1;
    myPCMFormat.mFramesPerPacket = 1;
    myPCMFormat.mBitsPerChannel = 16;
    myPCMFormat.mBytesPerPacket = 2;
    myPCMFormat.mBytesPerFrame = 2;
    
    
    AudioFileCreateWithURL((__bridge CFURLRef)self.flippedAudioUrl,
                       kAudioFileCAFType,
                       &myPCMFormat,
                       kAudioFileFlags_EraseFile,
                       &outputAudioFile);
    // set up input file
    AudioFileID inputAudioFile;
    OSStatus theErr = noErr;
    UInt64 fileDataSize = 0;
    
    AudioStreamBasicDescription theFileFormat;
    UInt32 thePropertySize = sizeof(theFileFormat);
    
    theErr = AudioFileOpenURL((__bridge CFURLRef)self.recordedAudioUrl,kAudioFileReadPermission, 0, &inputAudioFile);
    
    thePropertySize = sizeof(fileDataSize);
    theErr = AudioFileGetProperty(inputAudioFile, kAudioFilePropertyAudioDataByteCount, &thePropertySize, &fileDataSize);
    
    UInt32 dataSize = fileDataSize;
    void* theData = malloc(dataSize);
    
    //Read data into buffer
    UInt32 readPoint  = dataSize;
    UInt32 writePoint = 0;
    while( readPoint > 0 )
    {
       UInt32 bytesToRead = 2;
    
    AudioFileReadBytes( inputAudioFile, false, readPoint, &bytesToRead, theData );
    AudioFileWriteBytes( outputAudioFile, false, writePoint, &bytesToRead, theData );
    
    writePoint += 2;
    readPoint -= 2;
    }
    
    free(theData);
    AudioFileClose(inputAudioFile);
    AudioFileClose(outputAudioFile);
    

提交回复
热议问题