iOS @try @catch @finally 用法
程序员文章站
2022-04-06 16:02:54
...
音频caf 转 mp3 遇到一段神奇的代码如下:
#pragma mark - caf转mp3
- (void)audio_PCMtoMP3Result:(void(^)(NSData *))result
{
@try {
int read, write;
FILE *pcm = fopen([self.cafPathStr cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([self.mp3PathStr 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_in_samplerate(lame, 11025.0);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshorten-64-to-32"
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
#pragma clang diagnostic pop
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 {
NSLog(@"MP3生成成功: %@",self.mp3PathStr);
result([NSData dataWithContentsOfFile:self.mp3PathStr]);
}
}
@try @catch @finally 是个什么鬼东西?
大概分析一下代码逻辑如下:
@try {
... 逻辑处理
...执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容
}
@catch {
... 异常捕捉
...除非try里面执行代码发生了异常,否则这里的代码不会执行
}
@finally{
... 逻辑执行结果
...不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally
}
上一篇: ai中怎么绘制立体的3d物体模型?
下一篇: fireworks 质感按钮制作实例教程
推荐阅读
-
javascript中的try catch异常捕获机制用法分析
-
try-catch-finally 与返回值的修改
-
Python中的异常处理try/except/finally/raise用法分析
-
[VB.NET Tips]Try...Catch...End Try的另一种用法
-
实例解析js中try、catch、finally的执行规则
-
C#异常处理中try和catch语句及finally语句的用法示例
-
Java中try..catch..finally语句的使用
-
对try catch finally的理解
-
杂谈try-catch-finally异常处理
-
try(........){throw new Exception("xxxxxx")}........catch(){.........}用法