Recorte de audio iOS

Busqu茅 mucho y no pude encontrar nada relevante … Estoy trabajando en archivos de audio iOS y esto es lo que quiero hacer …

  1. Grabe el audio y guarde el clip (comprobado, hice esto usando AVAudioRecorder )
  2. Cambiar el tono (revisado, esto usando Dirac)
  3. Recortar 馃檨

Tengo dos marcadores, es decir, el inicio y el final del desplazamiento, y al usar esta informaci贸n, quiero recortar el archivo grabado y quiero guardarlo nuevamente. No quiero utilizar “buscar” porque m谩s adelante quiero reproducir todos los archivos grabados sincronizados (como los clips de pel铆cula flash en la l铆nea de tiempo) y, finalmente, quiero exportarlos como un solo archivo de audio.

Aqu铆 est谩 el c贸digo que he usado para recortar el audio de un archivo preexistente. Tendr谩 que cambiar las constantes relacionadas con M4A si ha guardado o est谩 guardando en otro formato.

 - (BOOL)trimAudio { float vocalStartMarker = ; float vocalEndMarker = ; NSURL *audioFileInput = ; NSURL *audioFileOutput = ; if (!audioFileInput || !audioFileOutput) { return NO; } [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL]; AVAsset *asset = [AVAsset assetWithURL:audioFileInput]; AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetAppleM4A]; if (exportSession == nil) { return NO; } CMTime startTime = CMTimeMake((int)(floor(vocalStartMarker * 100)), 100); CMTime stopTime = CMTimeMake((int)(ceil(vocalEndMarker * 100)), 100); CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime); exportSession.outputURL = audioFileOutput; exportSession.outputFileType = AVFileTypeAppleM4A; exportSession.timeRange = exportTimeRange; [exportSession exportAsynchronouslyWithCompletionHandler:^ { if (AVAssetExportSessionStatusCompleted == exportSession.status) { // It worked! } else if (AVAssetExportSessionStatusFailed == exportSession.status) { // It failed... } }]; return YES; } 

Tambi茅n hay Technical Q & A 1730 , que ofrece un enfoque un poco m谩s detallado.

Aqu铆 hay un c贸digo de muestra que recorta el archivo de audio desde el inicio y el final del desplazamiento y lo guarda de nuevo. Verifique este ajuste de audio iOS .

 // Path of your source audio file NSString *strInputFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"abc.mp3"]; NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath]; // Path of your destination save audio file NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryCachesDirectory = [paths objectAtIndex:0]; libraryCachesDirectory = [libraryCachesDirectory stringByAppendingPathComponent:@"Caches"]; NSString *strOutputFilePath = [NSString stringWithFormat:@"%@%@",libraryCachesDirectory,@"/abc.mp4"]; NSURL *audioFileOutput = [NSURL fileURLWithPath:strOutputFilePath]; if (!audioFileInput || !audioFileOutput) { return NO; } [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL]; AVAsset *asset = [AVAsset assetWithURL:audioFileInput]; AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetAppleM4A]; if (exportSession == nil) { return NO; } float startTrimTime = 0; float endTrimTime = 5; CMTime startTime = CMTimeMake((int)(floor(startTrimTime * 100)), 100); CMTime stopTime = CMTimeMake((int)(ceil(endTrimTime * 100)), 100); CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime); exportSession.outputURL = audioFileOutput; exportSession.outputFileType = AVFileTypeAppleM4A; exportSession.timeRange = exportTimeRange; [exportSession exportAsynchronouslyWithCompletionHandler:^ { if (AVAssetExportSessionStatusCompleted == exportSession.status) { NSLog(@"Success!"); } else if (AVAssetExportSessionStatusFailed == exportSession.status) { NSLog(@"failed"); } }]; 

importar siguiendo dos bibliotecas en .m

 #import "BJRangeSliderWithProgress.h" #import < AVFoundation/AVFoundation.h > 

y luego de pegar el siguiente c贸digo, podr谩s recortar un archivo de audio con la ayuda de dos pulgares.

 - (void) viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. mySlider = [[BJRangeSliderWithProgress alloc] initWithFrame:CGRectMake(20, 100, 300, 50)]; [mySlider setDisplayMode:BJRSWPAudioSetTrimMode]; [mySlider addTarget:self action:@selector(valueChanged) forControlEvents:UIControlEventValueChanged]; [mySlider setMinValue:0.0]; NSString *strInputFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"saewill.mp3"]; NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath]; audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:audioFileInput error:nil]; [mySlider setMaxValue:audioPlayer.duration]; [self.view addSubview:mySlider]; } -(void)valueChanged { NSLog(@"%f %f", mySlider.leftValue, mySlider.rightValue); } -(IBAction)playTheSong { // Path of your source audio file NSString *strInputFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"saewill.mp3"]; NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath]; // Path of your destination save audio file NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryCachesDirectory = [paths objectAtIndex:0]; //libraryCachesDirectory = [libraryCachesDirectory stringByAppendingPathComponent:@"Caches"]; NSString *strOutputFilePath = [libraryCachesDirectory stringByAppendingPathComponent:@"output.mov"]; NSString *requiredOutputPath = [libraryCachesDirectory stringByAppendingPathComponent:@"output.m4a"]; NSURL *audioFileOutput = [NSURL fileURLWithPath:requiredOutputPath]; [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL]; AVAsset *asset = [AVAsset assetWithURL:audioFileInput]; AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetAppleM4A]; float startTrimTime = mySlider.leftValue; float endTrimTime = mySlider.rightValue; CMTime startTime = CMTimeMake((int)(floor(startTrimTime * 100)), 100); CMTime stopTime = CMTimeMake((int)(ceil(endTrimTime * 100)), 100); CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime); exportSession.outputURL = audioFileOutput; exportSession.outputFileType = AVFileTypeAppleM4A; exportSession.timeRange = exportTimeRange; [exportSession exportAsynchronouslyWithCompletionHandler:^ { if (AVAssetExportSessionStatusCompleted == exportSession.status) { NSLog(@"Success!"); NSLog(@" OUtput path is \n %@", requiredOutputPath); NSFileManager * fm = [[NSFileManager alloc] init]; [fm moveItemAtPath:strOutputFilePath toPath:requiredOutputPath error:nil]; //[[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL]; NSURL *url=[NSURL fileURLWithPath:requiredOutputPath]; NSError *error; audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error]; audioPlayer.numberOfLoops=0; [audioPlayer play]; } else if (AVAssetExportSessionStatusFailed == exportSession.status) { NSLog(@"failed with error: %@", exportSession.error.localizedDescription); } }]; }