简体   繁体   中英

Why does my AVAudioPlayer not play sound?

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?

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

您是否尝试增加[player setVolume:1]值?

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