Manuel
Manuel

Reputation: 10303

AVAudioPlayer refuses to play modified wav file

The first time i call this method file1 will be nil and file2 will be returned. When this hapens the file will play normally (so the calling of this method should be fine). But when i call it for the second time it will return an NSURL which the AVAudioPlayer does not play. My guess is I have missed something in the header. In the debugging mode i have seen that the totalLength is exactly as long as the data's length.

+(NSURL *)mergeFile1:(NSURL *)file1 withFile2:(NSURL *)file2 {
    if(file1 == nil) {
        return [file2 copy];
    }

    NSData * wav1Data = [NSData dataWithContentsOfURL:file1];
    NSData * wav2Data = [NSData dataWithContentsOfURL:file2];

    int wav1DataSize = [wav1Data length] - 46;  
    int wav2DataSize = [wav2Data length] - 46;

    if (wav1DataSize <= 0 ||  wav2DataSize <= 0) {
        return nil;
    }   

    NSMutableData * soundFileData = [NSMutableData dataWithData:[wav1Data subdataWithRange:NSMakeRange(0, 46)]];
    [soundFileData appendData:[wav1Data subdataWithRange:NSMakeRange(46, wav1DataSize)]];
    [soundFileData appendData:[wav2Data subdataWithRange:NSMakeRange(46, wav2DataSize)]];

    unsigned int totalLength = [soundFileData length];

    NSLog(@"Calculated: %d - Real: %d", totalLength, [soundFileData length]);

    [soundFileData replaceBytesInRange:NSMakeRange(4, 4)
                             withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength-8)}];
    [soundFileData replaceBytesInRange:NSMakeRange(42, 4)
                             withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength)}];

    [soundFileData writeToURL:file1 atomically:YES];

    return [file1 copy];
}

If anyone sees something that can be of help it would be much appreciated! Any questions will be answered asap.

EDIT

I know there are 2 sorts of wav headers: 44 bytes or 46 bytes. I have tried both.

EDIT

I have looked at the Audio File Services Reference which contains a lot of nice stuff i might want to use, but i can't figure out how to use all this. I'm not really known with c. Hope anyone could help me out with this.

EDIT

An example of a merged wav file is found here: 7--443522512

Upvotes: 1

Views: 807

Answers (1)

Mattias Wadman
Mattias Wadman

Reputation: 11425

Looks like your WAV file includes a broken FLLR chunk before the data chunk, or at least VLC thinks the FLLR chunk is over 2GB large so it tries to skip to the next chunk which is beyond the file end.

Maybe you should try to create WAV files without FLLR chunk before merging, the kAudioFileFlags_DontPageAlignAudioData seams to make Audio File Services skip it.

Another option is to extract the data chunks and write a new wav file, a did a proof of concept implementation here: https://gist.github.com/1555889

Upvotes: 1

Related Questions