0
votes

My goal is to download a .mp3 file, and keep its bytes in memory, and have a player play it. I do not want to store the file on the device.

I download the file as such:

+(NSData*) downloadFile:(NSString*) urlString {
    NSURL *url = [NSURL URLWithString: urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10];
    [request setHTTPMethod:@"GET"];

    NSHTTPURLResponse* response;
    NSError* error = nil;

    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];

    return data;
}

This works fine. I can see the actual bytevalues in the debugger and in a hex editor, they are the same.

Then I wish to play them using AVAudioPlayer, as suggested by Apple's documentation:

NSData *mp3Bytes = result_of_downloadFile;
NSError *error;

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:mp3Bytes error:&error];
player.delegate = self;

BOOL success = [player prepareToPlay];
[player setVolume:1];
player.numberOfLoops = 1;
if (success) {
    NSLog(@"Play it, it takes %f seconds", [player duration]);
    BOOL playing = [player play];
    NSLog(@"Playing? %i", playing);

} else {
    NSLog(@"failed");
}

The log tells me that everything is fine, the prepareToPlay: succeeded, the play: succeeded, but no sound is heard.

This is on an actual device, ipad mini with ios 8.2 . It can play music using the ios Music app.

So, what about my playing code is incorrect?

2
did u try increasing the volume ?Dheeraj Singh

2 Answers

2
votes

It looks like your AVAudioPlayer is going out of scope and being deallocated. Turn it into a member variable to prolong its lifetime.

0
votes

Did you try increasing the [ player setVolume:1] value?