iOS的音频微调

问题描述 投票:10回答:4

我搜索了很多,但没有找到任何相关的...我在iOS上的音频文件工作,这里是我想做的事...

  1. 录音和保存剪辑(经过,我这样做是使用AVAudioRecorder
  2. 改变音高(查了一下,这篇利用狄拉克)
  3. 修剪:(

我有两个标志,即开始和结束偏移量,并使用这个信息,我想剪裁记录的文件,并要保存它回来。我不想用“闹”,因为后来我想同步的(就像在时间轴Flash影片剪辑)播放的所有记录文件,然后最后我要导出为一个音频文件。

ios audio crop seek trim
4个回答
27
投票

下面是我用从一个已经存在的文件修剪音频代码。你需要改变,如果你已经储存或保存为另一种格式的M4A有关的常数。

- (BOOL)trimAudio
{
    float vocalStartMarker = <starting time>;
    float vocalEndMarker = <ending time>;

    NSURL *audioFileInput = <your pre-existing file>;
    NSURL *audioFileOutput = <the file you want to create>;

    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;
}

还有Technical Q&A 1730,这给出了一个稍微更详细的方法。


2
投票

这是从开始和结束失调调整音频文件并将其保存回一个示例代码。请检查该iOS Audio Trimming

// 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");
    }
}];

2
投票

进口继.M两个库

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

和粘贴下面的代码后,你将能够修剪的音频文件有两个大拇指的帮助。

- (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);
           }
       }];

}

0
投票

//雨燕4.2

如果有人还在寻找答案迅速这里它是。

//音频微调

func trimAudio(asset: AVAsset, startTime: Double, stopTime: Double, finished:@escaping (URL) -> ())
{

        let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith:asset)

        if compatiblePresets.contains(AVAssetExportPresetMediumQuality) {

        guard let exportSession = AVAssetExportSession(asset: asset, 
        presetName: AVAssetExportPresetAppleM4A) else{return}

        // Creating new output File url and removing it if already exists.
        let furl = createUrlInAppDD("trimmedAudio.m4a") //Custom Function
        removeFileIfExists(fileURL: furl) //Custom Function

        exportSession.outputURL = furl
        exportSession.outputFileType = AVFileType.m4a

        let start: CMTime = CMTimeMakeWithSeconds(startTime, preferredTimescale: asset.duration.timescale)
        let stop: CMTime = CMTimeMakeWithSeconds(stopTime, preferredTimescale: asset.duration.timescale)
        let range: CMTimeRange = CMTimeRangeFromTimeToTime(start: start, end: stop)
        exportSession.timeRange = range

        exportSession.exportAsynchronously(completionHandler: {

            switch exportSession.status {
            case .failed:
                print("Export failed: \(exportSession.error!.localizedDescription)")
            case .cancelled:
                print("Export canceled")
            default:
                print("Successfully trimmed audio")
                DispatchQueue.main.async(execute: {
                    finished(furl)
                })
            }
        })
    }
}

你可以使用它的视频修剪也是如此。对于视频修剪作为波纹管替代出口会话的价值:

守卫让exportSession = AVAssetExportSession(资产:资产,presetName:AVAssetExportPresetPassthrough)其他{}回报

和文件类型为MP4

exportSession.outputFileType = AVFileType.mp4

© www.soinside.com 2019 - 2024. All rights reserved.