Как уменьшить размер аудиофайла в IOS

Я делаю приложение, которое получает песни из mediapicker и сохраняет его в своем приложении.я хочу уменьшить размер файла,но у меня есть образец с именем "AACConverter", я тестирую приложение, но он не уменьшает размер файла.может ли один помочь мне в решении этой проблемы.

- (IBAction)convert:(id)sender {
    if ( ![TPAACAudioConverter AACConverterAvailable] ) {
        [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Converting audio", @"")
                                     message:NSLocalizedString(@"Couldn't convert audio: Not supported on this device", @"")
                                    delegate:nil
                           cancelButtonTitle:nil
                           otherButtonTitles:NSLocalizedString(@"OK", @""), nil] autorelease] show];
        return;
    }

    // Initialise audio session, and register an interruption listener, important for AAC conversion
    if ( !checkResult(AudioSessionInitialize(NULL, NULL, interruptionListener, self), "initialise audio session") ) {
        [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Converting audio", @"")
                                 message:NSLocalizedString(@"Couldn't initialise audio session!", @"")
                                delegate:nil
                       cancelButtonTitle:nil
                       otherButtonTitles:NSLocalizedString(@"OK", @""), nil] autorelease] show];
        return;
    }


    // Set up an audio session compatible with AAC conversion.  Note that AAC conversion is incompatible with any session that provides mixing with other device audio.
    UInt32 audioCategory = kAudioSessionCategory_MediaPlayback;
    if ( !checkResult(AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(audioCategory), &audioCategory), "setup session category") ) {
        [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Converting audio", @"")
                                 message:NSLocalizedString(@"Couldn't setup audio category!", @"")
                                delegate:nil
                       cancelButtonTitle:nil
                       otherButtonTitles:NSLocalizedString(@"OK", @""), nil] autorelease] show];
        return;
    } 

    NSArray *documentsFolders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    audioConverter = [[[TPAACAudioConverter alloc] initWithDelegate:self 
                                                             source:[[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"]
                                                        destination:[[documentsFolders objectAtIndex:0] stringByAppendingPathComponent:@"audio.m4a"]] autorelease];



    NSLog(@"destinatiion path is %@",[[documentsFolders objectAtIndex:0]stringByAppendingFormat:@"audio.m4a"]);
    ((UIButton*)sender).enabled = NO;
    [self.spinner startAnimating];
    self.progressView.progress = 0.0;
    self.progressView.hidden = NO;

    [audioConverter start];
}

- (IBAction)playConverted:(id)sender {
    if ( audioPlayer ) {
        [audioPlayer stop];
        [audioPlayer release];
        audioPlayer = nil;
        [(UIButton*)sender setTitle:@"Play converted" forState:UIControlStateNormal];
    } else {
        NSArray *documentsFolders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [[documentsFolders objectAtIndex:0] stringByAppendingPathComponent:@"audio.m4a"];
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        [audioPlayer play];

        [(UIButton*)sender setTitle:@"Stop" forState:UIControlStateNormal];
    }
}

- (IBAction)emailConverted:(id)sender {
    NSArray *documentsFolders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[documentsFolders objectAtIndex:0] stringByAppendingPathComponent:@"audio.m4a"];

    MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
    mailController.mailComposeDelegate = self;
    [mailController setSubject:NSLocalizedString(@"Recording", @"")];
    [mailController addAttachmentData:[NSData dataWithContentsOfMappedFile:path] 
                             mimeType:@"audio/mp4a-latm"
                             fileName:[path lastPathComponent]];

    [self presentModalViewController:mailController animated:YES];
}

#pragma mark - Audio converter delegate

-(void)AACAudioConverter:(TPAACAudioConverter *)converter didMakeProgress:(CGFloat)progress {
    self.progressView.progress = progress;
}

-(void)AACAudioConverterDidFinishConversion:(TPAACAudioConverter *)converter {
    self.progressView.hidden = YES;
    [self.spinner stopAnimating];
    self.convertButton.enabled = YES;
    self.playConvertedButton.enabled = YES;
    self.emailConvertedButton.enabled = YES;
    audioConverter = nil;
}

-(void)AACAudioConverter:(TPAACAudioConverter *)converter didFailWithError:(NSError *)error {
    [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Converting audio", @"")
                                 message:[NSString stringWithFormat:NSLocalizedString(@"Couldn't convert audio: %@", @""), [error localizedDescription]]
                                delegate:nil
                       cancelButtonTitle:nil
                       otherButtonTitles:NSLocalizedString(@"OK", @""), nil] autorelease] show];
    self.convertButton.enabled = YES;
    audioConverter = nil;
}

2 ответов


существуют различные способы, которыми вы можете решить эту проблему. Если вы хотите, чтобы звук воспроизводился в фоновом режиме, вы можете использовать

[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@ " BGM.mp3 " loop: YES];

используя это, вы можете использовать небольшой аудиоклип, который будет небольшим по размеру, и воспроизводить его в цикле. То же самое можно применить и к эффекту звука.

кроме того, уменьшение битрейта аудиоклипа также помогает уменьшить размер файл. Для всех этих операций редактирования, которые включают редактирование/обрезку / обрезку звукового клипа, уменьшение битрейта, сохранение в разных форматах, я бы предложил вам использовать

смелость (открытым исходным кодом, бесплатно)


Если вы заботитесь о размере над качеством, возможно, вы хотите передать песню в формат amr.