Yahav Zamari Yahav Zamari - 6 months ago 36
Objective-C Question

Objective c - play mp3 stream frame by frame from memory buffer

I would like to play mp3 audio stream by submitting audio frames one by one.
I must submit it from memory buffer - without using mp3 file url (let's say that the mp3 streamed from the network and arrived in memory buffers).

Where from should I start?
Is there any sample code that does this kind of thing?

Answer

So it seems to be much simpler than i thought...

I just created:

    AVAudioPlayer* oAudioPlayer;

and the initialised it with data:

    oAudioPlayer = [[AVAudioPlayer alloc] initWithData:chunk fileTypeHint:AVFileTypeMPEGLayer3 error:&error];

while chunk is some mp3 frames arrived from the network.

and eventually the playing method:

    if ([oAudioPlayer play] == false)
        NSLog(@"failed to play audio buffer");

If one wants to have a callback when frame has been finished to be played he can add a delegate before playing:

    oAudioPlayer.delegate = oSound;

while oSound is a class:

    @interface    SoundClass : NSObject <AVAudioPlayerDelegate> {}

    @property(nonatomic,retain) AVAudioPlayer *player;

    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
    - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error;

    @end

It seems that the audio player needs big buffers (i needed at least two frames in a raw to hear the sound).

Currently, the audio doesn't sound good enough but i guess it is something with the data feeding i'm doing wrong.

Comments