Swift records multiple audio and converts audio to MP3 and synthesizes multiple MP3 files as one file

Source: Internet
Author: User
Tags uikit

My requirement is to be able to record multiple files, the last generated file format is mp3 form, looked up the various information, because Swift cannot directly record the audio as the MP3 format, so finally I took the solution to the first to convert each individual file to MP3, and finally merged to form a MP3 file

First, the first step is recorded in simple instructions:

Reference: http://www.jianshu.com/p/09af208a5663 (thanks) http://www.hangge.com/blog/cache/detail_772.html (thank you)

1. Audio configuration, I tried to add as many configurations as possible at the end of the problem, the configuration of the test success is as follows

Recorderseetingsdic: [String:any] = [        avsampleratekey:nsnumber (value:16000),//Sample rate        Avformatidkey:nsnumber ( VALUE:KAUDIOFORMATLINEARPCM),//Audio format        avnumberofchannelskey:nsnumber (value:2),//channel number        Avencoderaudioqualitykey:nsnumber (Value:AVAudioQuality.min.rawValue)//recording quality]

2, recording implementation (part of the code)

Audio path Let audiopath = (Nssearchpathfordirectoriesindomains (. Documentdirectory,. Userdomainmask, True). First. Appending ("/TEST.CAF"))!


Let session:avaudiosession = Avaudiosession.sharedinstance () try! Session.setcategory (Avaudiosessioncategoryplayandrecord) try! Session.setactive (True) do {                recorder = try Avaudiorecorder (Url:url (String:audiopath)!, settings: Recorderseetingsdic)                                //Turn on the meter count function                recorder!. Ismeteringenabled = True                //Prepare the recording                recorder!. Preparetorecord ()                recorder? Record ()            } catch let err {                print ("Recording failed: \ (err.localizeddescription)")}

The second step is to convert the recorded multiple CAF format audio to a MP3 file (the first way is to synthesize multiple. caf files into a m4a file but can't find the solution m4a to MP3, with lame also does not work, very depressed)

1. First to compile lame this is the first step to convert the. CAF to MP3, there are many ways to refer

I refer to the compilation method: http://blog.csdn.net/cating1314/article/details/46046497 (Thank you)

We need to compile the Libmp3lame.a and lame.h two files, both in the compiled Thin-lame and fat-lame files. Choose according to your own needs, I use two files in Fat-lame

Do not want to compile words can adopt mine, should also not have what problem https://pan.baidu.com/s/1dFepCIl extract password: Reck

2 Conversion and synthesis methods (both conversion and synthesis are written in OC)

Reference: Https://github.com/CharmingLee/RecordingDemo (thank you)

Two files defined convertMp3.h and CONVERTMP3.M

ConvertMp3.h file


#import <UIKit/UIKit.h> @interface convertmp3:nsobject-(void) audioPCMtoMP3: (NSString *) Audiofilesavepath Mp3file: (NSString *) Mp3filepath mergefile: (NSString *) Mergefilepath; @end


#import "ConvertMp3.h" #import "lame.h" #define KFILESIZE (1 * 1024x768 * 1024x768) @interface convertMp3 () @end @implementation convertmp3-(void) audioPCMtoMP3:(NSString *) Audiofilesavepath mp3file: (NSString *) Mp3filepath mergefile: (NSString *)                mergefilepath{@try {int read, write;  FILE *PCM = fopen ([Audiofilesavepath cstringusingencoding:1], "RB");                                   Source converted audio File location fseek (PCM, 4*1024, seek_cur);  Skip file header File *mp3 = fopen ([Mp3filepath cstringusingencoding:1], "WB");        MP3 file location generated by output outputs const int pcm_size = 8192;        const int mp3_size = 8192;        short int pcm_buffer[pcm_size*2];                unsigned char mp3_buffer[mp3_size];        lame_t lame = Lame_init ();        Lame_set_in_samplerate (Lame, 16000);        LAME_SET_VBR (Lame, vbr_off);                Lame_init_params (lame);                do {read = (int.) fread (Pcm_buffer, 2*sizeof (short int), pcm_size, PCM);        if (read = = 0) write = Lame_encode_flush (lame, mp3_buffer, mp3_size);                        else Write = lame_encode_buffer_interleaved (Lame,pcm_buffer, read, Mp3_buffer, mp3_size);        Fwrite (Mp3_buffer, Write, 1, mp3);                } while (read! = 0);        Lame_close (lame);        Fclose (mp3);    Fclose (PCM);    } @catch (NSException *exception) {NSLog (@ "%@", [exception description]); } @finally {//from the second file to begin merging the first file Mergefilepath the same as Mp3filepath the first converted file address is the full MP3 file address of the final composition if ([Mergefilepa        th Isequaltostring:mp3filepath] = = NO) {[self piecefilea:mergefilepath withfileb:mp3filepath]; }}}-(BOOL) Piecefilea: (NSString *) Filepatha Withfileb: (NSString *) FILEPATHB {//After the file path has been synthesized, no matter how many files are in this Filepat        NSString *synthesisfilepath = Filepatha after the ha file continues to be written;    Updated way to read file a nsfilehandle *handlea = [Nsfilehandle Filehandleforupdatingatpath:synthesisfilepath]; [Handlea SeektoEndoffile];                                                     Nsdictionary *filebdic = [[Nsfilemanager Defaultmanager] Attributesofitematpath:filepathb    Error:nil];        Long Long Filesizeb = filebdic.filesize; Greater than XM Shard stitching xm if (Filesizeb > Kfilesize) {//shard long long pieces = filesizeb/kfilesize;//    Whole piece long long let = Filesizeb% Kfilesize;        Remaining slices long long sizes = pieces;        Excess if (Let > 0) {//Gator piece Sizes + = 1;        } nsfilehandle *handleb = [Nsfilehandle FILEHANDLEFORREADINGATPATH:FILEPATHB];            for (int i = 0; i < sizes; i++) {[Handleb seektofileoffset:i * kfilesize];            NSData *tmp = [Handleb readdataoflength:kfilesize];        [Handlea writedata:tmp];                } [Handleb Synchronizefile]; Greater than XM Shard Read XM (last possibly less than XM)} else {[Handlea writedata:[nsdata datawithcontentsOFFILE:FILEPATHB]];     } [Handlea Synchronizefile];    NSLog (@ "merge complete");        Delete the B file//[[Nsfilemanager Defaultmanager] REMOVEITEMATPATH:FILEPATHB Error:nil]; return YES;} @end

Add a header file to the bridge file #import "convertMp3.h"

  3. Call OC file to start merging


Merge    func Transferaudio (num:int) {let                Documentdirectoryurl = FileManager.default.urls (for:. Documentdirectory, in:. Userdomainmask). first! As Nsurl let        stringdate = Basecontroller (). Getcurrenttimemillisecond () let        Mp3path:url = ( Documentdirectoryurl.appendingpathcomponent (Basecontroller (). RandomMD5 (str:stringdate) + ". mp3")! As URL as Nsurl) as url!                If num = = 0 {            Self.audiopath = Mp3path.path        }                convertMp3 (). AudioPCMtoMP3 (Self.audiolocalurls[num], Mp3file:mp3path.path,mergefile:self.audiopath)                If num = = self.audiolocalurls.count-1{            self.uploadaudio ()/ /upload        }else{let            order = num + 1            transferaudio (num:order)        }    }

Call Transferaudio (num:0) to start a one CAF file conversion merge so that the process goes through recording multiple CAF files individually to convert them to mp3 in the merge into a full mp3 file, just contact Swift not much time patchwork implemented function if there's something wrong Hope to tell me in time thank you, hope for other needs of the people have a reference, after all, torture me for a long time


Swift records multiple audio and converts audio to MP3 and synthesizes multiple MP3 files as one file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.