0

I have audio player. I download audio in this way

- (void) song{
if (_index == 0) {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"1.mp3"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:NO];

if (!fileExists) {
    NSString *stringURL = @"https://drive.google.com/uc?export=download&id=0B6zMam2kAK39VHZ1cUZsM3BhQXM";
    NSURL  *url = [NSURL URLWithString:stringURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    [urlData writeToFile:filePath atomically:YES];
}

self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
}
}

But when audio downloading I can’t do anything. User interface stop. How can download audio and do anything in user interface simultaneously?

user
  • 53
  • 7
  • 2
    Never download/upload from/to the Internet on the main thread. Always use a background thread. – rmaddy Mar 31 '16 at 19:35

3 Answers3

0

You are downloading the file in the main thread. you need to make an asynchronous call in order to avoid stopping UI.

touti
  • 1,164
  • 6
  • 18
0

Give your method a block to execute when finished, then run the download code in the background. Lets say, for your case the output is a local file with the downloaded content:

- (void)songWithCompletion:(void (^)(NSString *))completion {
    NSString *filePath = [self song];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (completion) completion(filePath);
    });
}

Change the song method to return filePath. Don't ever call it directly, only via songWithCompletion.

- (void)song {
    // ... your code from the OP
    // don't allocate the audio player here, just return the local file
    return filePath;
} 

Call it like this...

[self songWithCompletion:^(NSString *filePath) {
    if (filePath) {
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
        // you should really handle audio player error here, too
    } else {
        // handle error
    }
}];
danh
  • 62,181
  • 10
  • 95
  • 136
  • I understand this is not welcomed by the community. But could you please help with this problem. I just don't know what to do. Thanks! - https://stackoverflow.com/questions/69851479/audio-files-wont-play-with-airpods-pro-on-ios-15 – user Nov 12 '21 at 20:37
0
-(void)downloadAudio 
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://drive.google.com/uc?export=download&id=0B6zMam2kAK39VHZ1cUZsM3BhQXM"]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if (theConnection) {        
    receivedData = [NSMutableData data] ;  
} else {NSLog(@"no connection!");
}



- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

NSLog(@"Succeed! Received %d bytes of data",[receivedData length]);

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSLog(@"%@", [documentPaths objectAtIndex:0]);
NSString *documentDirectoryPath = [documentPaths objectAtIndex:0];
NSString *folderPath = [documentDirectoryPath stringByAppendingPathComponent:@"audioFile.mp3"];
[receivedData writeToFile:folderPath atomically:YES];
    NSURL *soundURL = [NSURL fileURLWithPath:folderPath];
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:folderPath]) {

    player = [[AVAudioPlayer alloc]initWithContentsOfURL:soundURL error:&error];
    player.volume=0.5;
    NSError *error = nil;
    if (!error) {
        [player play];
        NSLog(@"File is playing!");
    }
    else{
        NSLog(@"Error in creating audio player:%@",[error description]);
    }
}
else{
    NSLog(@"File doesn't exist");
}

}
isKrishnaK
  • 393
  • 3
  • 10