简体   繁体   中英

On iPhone, how can I use fileHandle to download a mp3 file on the fly?

I am trying to implement the AudioFileStreamSeek feature on my streaming app. But there is no way I can get this running. Even Matt Gallagher said on his blog:

Icidentally, the AudioFileStreamSeek function seems completely broken. If you can't get it to work (as I couldn't) just seek to a new point in the file, set discontinuous to true and let AudioFileStream deal with it.

My code kindda looks like this but I can't get it to work:

    NSString *path = [[NSString alloc] initWithContentsOfURL: url];

    NSLog(@"url = %@", path);
    SInt64 currentOffset;
    UInt32 flags = 0;

    OSStatus status = AudioFileStreamSeek( audioFileStream, 150, &currentOffset, &flags );
    NSLog(@"Setting next byte offset to: %qi, flags: %d", (long long)currentOffset, flags);

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath: path];
    // then read data from the new offset set by AudioFileStreamSeek
    [fileHandle seekToFileOffset:currentOffset];
    NSData * data = [fileHandle readDataOfLength:4096];

    NSLog(@"data length %d, bytes %d", [data length], [data bytes]);


    if (discontinuous)
    {
        err = AudioFileStreamParseBytes(audioFileStream, length, bytes, kAudioFileStreamParseFlag_Discontinuity);
        if (err)
        {
            [self failWithErrorCode:AS_FILE_STREAM_PARSE_BYTES_FAILED];
            return;
        }
    }
    else
    {
        err = AudioFileStreamParseBytes(audioFileStream, length, bytes, 0);
        if (err)
        {
            [self failWithErrorCode:AS_FILE_STREAM_PARSE_BYTES_FAILED];
            return;
        }
    }

Please help...

Lacking any other solutions, what you can do is create an NSConnection and then as you receive the NSData you can effectively create streaming by processing each new chunk of NSData that you receive to your NSConnectionDelegate. NSConnection will make sure to send it to you in order, so you won't have to worry about getting it ordered correctly. Note though that, depending on your application, you may need to do this outside the main application thread, so that the user can still work with your app even if the download stalls and you have to rebuffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM