zjf
2023-03-06 392b76515f40376b6d36f40a114850ef63650384
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
//
//  ConvertAudioFile.m
//  Expert
//
//  Created by xuxiwen on 2017/3/21.
//  Copyright © 2017年 xuxiwen. All rights reserved.
//
 
#import "ConvertAudioFile.h"
#import <lame/lame.h>
 
@interface ConvertAudioFile ()
@property (nonatomic, assign) BOOL stopRecord;
@end
 
@implementation ConvertAudioFile
 
/**
 get instance obj
 
 @return ConvertAudioFile instance
 */
+ (instancetype)sharedInstance {
    static ConvertAudioFile *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ConvertAudioFile alloc] init];
    });
    return instance;
}
 
/**
 ConvertMp3
 
 @param cafFilePath caf FilePath
 @param mp3FilePath mp3 FilePath
 @param sampleRate sampleRate (same record sampleRate set)
 @param callback callback result
 */
//- (void)conventToMp3WithCafFilePath:(NSString *)cafFilePath
//                        mp3FilePath:(NSString *)mp3FilePath
//                         sampleRate:(int)sampleRate
//                           callback:(void(^)(BOOL result))callback
//{
//
//        NSLog(@"convert begin!!");
//    __weak typeof(self) weakself = self;
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//        weakself.stopRecord = NO;
//
//        @try {
//
//            int read, write;
//
//            FILE *pcm = fopen([cafFilePath cStringUsingEncoding:NSASCIIStringEncoding], "rb");
//            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:NSASCIIStringEncoding], "wb+");
//
//            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, sampleRate);
//            lame_set_VBR(lame, vbr_default);
//            lame_init_params(lame);
//
//            long curpos;
//            BOOL isSkipPCMHeader = NO;
//
//            do {
//                curpos = ftell(pcm);
//                long startPos = ftell(pcm);
//                fseek(pcm, 0, SEEK_END);
//                long endPos = ftell(pcm);
//                long length = endPos - startPos;
//                fseek(pcm, curpos, SEEK_SET);
//
//                if (length > PCM_SIZE * 2 * sizeof(short int)) {
//
//                    if (!isSkipPCMHeader) {
//                        //Uump audio file header, If you do not skip file header
//                        //you will heard some noise at the beginning!!!
//                        fseek(pcm, 4 * 1024, SEEK_CUR);
//                        isSkipPCMHeader = YES;
//                        NSLog(@"skip pcm file header !!!!!!!!!!");
//                    }
//
//                    read = (int)fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
//                    write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
//                    fwrite(mp3_buffer, write, 1, mp3);
////                    NSLog(@"read %d bytes", write);
//                } else {
//                    [NSThread sleepForTimeInterval:0.05];
////                    NSLog(@"sleep");
//                }
//
//            } while (! weakself.stopRecord);
//
//            read = (int)fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
//            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
//
//            NSLog(@"read %d bytes and flush to mp3 file", write);
//            lame_mp3_tags_fid(lame, mp3);
//
//            lame_close(lame);
//            fclose(mp3);
//            fclose(pcm);
//        }
//        @catch (NSException *exception) {
//            NSLog(@"%@", [exception description]);
//            if (callback) {
//                callback(NO);
//            }
//        }
//        @finally {
//            if (callback) {
//                callback(YES);
//            }
//            NSLog(@"convert mp3 finish!!! %@", mp3FilePath);
//        }
//    });
//
//}
 
/**
 send end record signal
 */
- (void)sendEndRecord {
    self.stopRecord = YES;
}
 
- (void)conventToMp3WithCafFilePath:(NSString *)cafFilePath
                        mp3FilePath:(NSString *)mp3FilePath
                         sampleRate:(int)sampleRate {
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        weakself.stopRecord = NO;
        @try {
            int read, write;
            FILE *pcm = fopen([cafFilePath cStringUsingEncoding:NSASCIIStringEncoding], "rb");
            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:NSASCIIStringEncoding], "wb+");
            
            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, sampleRate);
            lame_set_VBR(lame, vbr_default);
            lame_init_params(lame);
            
            long curpos;
            BOOL isSkipPCMHeader = NO;
            
            do {
                curpos = ftell(pcm);
                long startPos = ftell(pcm);
                fseek(pcm, 0, SEEK_END);
                long endPos = ftell(pcm);
                long length = endPos - startPos;
                fseek(pcm, curpos, SEEK_SET);
                
                if (length > PCM_SIZE * 2 * sizeof(short int)) {
                    
                    if (!isSkipPCMHeader) {
                        //Uump audio file header, If you do not skip file header
                        //you will heard some noise at the beginning!!!
                        fseek(pcm, 4 * 1024, SEEK_CUR);
                        isSkipPCMHeader = YES;
                        NSLog(@"skip pcm file header !!!!!!!!!!");
                    }
                    
                    read = (int)fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
                    write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
                    fwrite(mp3_buffer, write, 1, mp3);
                    //                    NSLog(@"read %d bytes", write);
                } else {
                    [NSThread sleepForTimeInterval:0.05];
                    //                    NSLog(@"sleep");
                }
            } while (! weakself.stopRecord);
                NSLog(@"停止录音回调-----");
                read = (int)fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
                NSLog(@"read %d bytes and flush to mp3 file", write);
                lame_mp3_tags_fid(lame, mp3);
                lame_close(lame);
                fclose(mp3);
                fclose(pcm);
        }
        @catch (NSException *exception) {
            NSLog(@"出错了");
            NSLog(@"%@", [exception description]);
        
        }
        @finally {
            NSLog(@"转码完成");
            NSLog(@"convert mp3 finish!!! %@", mp3FilePath);
        }
    });
}
 
#pragma mark - ----------------------------------
 
// 这是录完再转码的方法, 如果录音时间比较长的话,会要等待几秒...
// Use this FUNC convent to mp3 after record
 
+ (void)conventToMp3WithCafFilePath:(NSString *)cafFilePath
                        mp3FilePath:(NSString *)mp3FilePath
                         sampleRate:(int)sampleRate
                           callback:(void(^)(BOOL result))callback
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        @try {
            int read, write;
            
            FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
            fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb+");  //output 输出生成的Mp3文件位置
            
            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_num_channels(lame,1);//设置1为单通道,默认为2双通道
            lame_set_in_samplerate(lame, sampleRate);
            lame_set_VBR(lame, vbr_default);
            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_mp3_tags_fid(lame, mp3);
 
            lame_close(lame);
            fclose(mp3);
            fclose(pcm);
        }
        @catch (NSException *exception) {
            NSLog(@"%@",[exception description]);
            if (callback) {
                callback(NO);
            }
        }
        @finally {
            NSLog(@"-----\n  MP3生成成功: %@   -----  \n", mp3FilePath);
            if (callback) {
                callback(YES);
            }
        }
    });
}
 
@end