SoFunction
Updated on 2025-05-20

Code examples for intercepting and splitting audio and video in iOS

Code examples for intercepting and splitting audio and video in iOS

Updated: May 20, 2025 08:26:47 Author: Chenzai, born in the 1990s
In iOS development, intercepting or segmenting audio and video is a common requirement, suitable for short video editing, voice message cropping, media content editing and other scenarios. This function can be efficiently implemented using the AVFoundation framework. The following will introduce in detail how to intercept or segment audio and video in iOS, and provide complete code examples and usage methods. Friends who need it can refer to it.

Core idea

The core steps for intercepting or segmenting audio and video are as follows:

  • Load original audio and video filesAVURLAsset
  • Set the time rangeCMTimeRange) Specify the start time and duration to be intercepted
  • Create an export sessionAVAssetExportSession
  • Export the target file(support.mp4.m4aetc.)
  • Handle asynchronous export completion callback

Video Intercept Example (Objective-C)

- (void)trimVideoFromURL:(NSURL *)inputURL startTime:(NSTimeInterval)startTime duration:(NSTimeInterval)duration completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    // 1. Create an export session    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
    
    // 2. Set the output path and file format    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"trimmedVideo.mp4"];
     = [NSURL fileURLWithPath:outputPath];
     = AVFileTypeMPEG4;
    
    // 3. Set the time range (start ~ start + duration)    CMTime startCMTime = CMTimeMakeWithSeconds(startTime, 600);
    CMTime durationCMTime = CMTimeMakeWithSeconds(duration, 600);
    CMTimeRange timeRange = CMTimeRangeMake(startCMTime, durationCMTime);
     = timeRange;
    
    // 4. Asynchronous export    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if ( == AVAssetExportSessionStatusCompleted) {
            NSLog(@"Video intercepted successfully: %@", outputPath);
            if (completion) completion([NSURL fileURLWithPath:outputPath], nil);
        } else {
            NSError *error = ;
            NSLog(@"Video interception failed: %@", );
            if (completion) completion(nil, error);
        }
    }];
}

How to use

NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myVideo" ofType:@"mp4"]];
[self trimVideoFromURL:videoURL startTime:5.0 duration:10.0 completion:^(NSURL *outputURL, NSError *error) {
    if (outputURL) {
        NSLog(@"Intercepted video path: %@", );
    }
}];

Audio intercepting example (Objective-C)

- (void)trimAudioFromURL:(NSURL *)inputURL startTime:(NSTimeInterval)startTime duration:(NSTimeInterval)duration completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetAppleM4A];
    
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"trimmedAudio.m4a"];
     = [NSURL fileURLWithPath:outputPath];
     = AVFileTypeAppleM4A;
    
    CMTime startCMTime = CMTimeMakeWithSeconds(startTime, 600);
    CMTime durationCMTime = CMTimeMakeWithSeconds(duration, 600);
    CMTimeRange timeRange = CMTimeRangeMake(startCMTime, durationCMTime);
     = timeRange;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if ( == AVAssetExportSessionStatusCompleted) {
            NSLog(@"Audio interception successfully: %@", outputPath);
            if (completion) completion([NSURL fileURLWithPath:outputPath], nil);
        } else {
            NSError *error = ;
            NSLog(@"Audio interception failed: %@", );
            if (completion) completion(nil, error);
        }
    }];
}

How to use

NSURL *audioURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myAudio" ofType:@"mp3"]];
[self trimAudioFromURL:audioURL startTime:3.0 duration:5.0 completion:^(NSURL *outputURL, NSError *error) {
    if (outputURL) {
        NSLog(@"Intercepted audio path: %@", );
    }
}];

Things to note

project illustrate
Time unit useCMTimeMakeWithSecondsConvert seconds toCMTime
Output path useNSTemporaryDirectory()Avoid storage problems
Output format Video recommendation.mp4, audio recommendation.m4aor.caf
Export performance useAVAssetExportPresetLowQualityCan improve processing speed
Error handling examineand

Extension suggestions

  • Multi-fragment splicing: Can be combinedAVMutableCompositionRealize multi-section cropped content splicing.
  • Background export: It is recommended to execute large files in the background thread to avoid blocking the main thread.
  • Third-party library: If you need more complex editing functions, you can useFFmpeg-iOSorGPUImage

Summarize

passAVAssetExportSessionoftimeRangeProperties, you can easily intercept content from any time period from audio and video files. This method is suitable for both audio and video, with good compatibility and performance, and is one of the basic skills in iOS audio and video processing.

The above is the detailed content of the code example for intercepting and segmenting audio and video in iOS. For more information about intercepting and segmenting audio and video in iOS, please pay attention to my other related articles!

  • iOS
  • Intercept
  • segmentation
  • Audio and video

Related Articles

  • Detailed explanation of using jquery. Realize the internationalization of the web front-end

    This article mainly introduces the use of jquery. To realize the internationalization of the web front-end, it has certain reference value. If you are interested, you can learn about it.
    2017-07-07
  • iOS uses UIScrollView to achieve infinite scrolling effect

    This article mainly introduces to you how iOS uses UIScrollView to achieve infinite scrolling. First of all, it should be noted that the text is a "stupid way", but it is easy to understand and easy to implement, so it is okay to use it when there are not many pictures. Interested friends, follow the editor to study and study.
    2016-12-12
  • Detailed explanation of the comparison of two image compression methods when uploading pictures in IOS development

    This article mainly introduces the comparison of two image compression methods when uploading pictures in IOS development. Friends who need it can refer to it
    2017-03-03
  • Detailed explanation of the specification use of weak and strong modifiers for iOS development skills

    This article mainly introduces the detailed explanation of the standard use of weak and strong modifiers for iOS development skills. Friends in need can refer to it for reference. I hope it can be helpful. I wish you more progress and get promoted as soon as possible to get a salary increase as soon as possible.
    2022-07-07
  • IOS realizes the menu bar effect at the bottom of the chat interface

    This article shares with you the chat information interface in Boss Direct Recruitment. The main idea is to constrain animations and implement the code is relatively simple. The following editor will share with you the IOS menu bar effect at the bottom of the chat interface through this article. If you need it, please refer to it.
    2017-09-09
  • iOS get mobile phone IP address code

    This article mainly introduces the relevant code for iOS to obtain the IP address of the mobile terminal, which has certain reference value. Interested friends can refer to it.
    2016-11-11
  • Detailed explanation of the basic operations and usage of NSURL in IOS development

    NSURL is actually the website address we see on the browser. Isn’t this just a string? Why do you still need to write an NSURL? It’s mainly because the strings of the website address are relatively complex, including many request parameters. In this way, each department needs to be parsed during the request process, so encapsulating an NSURL is very convenient to operate.
    2015-12-12
  • iOS gets the content size of the webview in the cell

    This article mainly introduces the size of webview content in iOS to obtain the content size of webview in cell, which has certain reference value. Interested friends can refer to it.
    2016-09-09
  • Mac Charles bag capture tool detailed introduction

    This article mainly introduces the relevant information on the detailed introduction of the Mac Charles package grab tool. This briefly introduces the basic knowledge such as how to install and use. Friends who need it can refer to it.
    2016-12-12
  • Detailed explanation of the IOS code volume modification example

    This article mainly introduces the detailed explanation of the IOS code modification example. Friends who need it can refer to it.
    2017-05-05

Latest Comments