iOS AVAudioRecorder的應用

IOS 錄音AVAudioRecorder

144? 作者 qilinit 關注

2016.09.07 23:41 字數 208 閱讀 112評論 0喜歡 0

1、懶加載一個AVAudioRecorer類對象

2、設置保存的沙盒地址

3、將沙盒的地址轉換成NSURl對象

4、用字典設置屬性

5、創建對象

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}

/**

*? 懶加載avaudiorecorder對象

*

*? @return AVAudioRecorer

*/

-(AVAudioRecorder *)recorder

{

if (_recorder == nil) {

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *filePath = [path stringByAppendingPathComponent:@"123.caf"];

self.pathUILable.text = filePath;

NSLog(@"%@",filePath);

NSURL *url = [NSURL URLWithString:filePath];

NSDictionary *settingRecorder = @{AVFormatIDKey:@(kAudioFormatLinearPCM),AVSampleRateKey : @(8000)};

self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settingRecorder error:nil];

}

return _recorder;

}

/**

*? 開始錄音

*

*? @param sender void

*/

- (IBAction)recorder:(id)sender {

[self.recorder record];

}

- (IBAction)stopRecorder:(id)sender {

[self.recorder stop];

}

@end

#import<AVFoundation/AVFoundation.h>

#include "lame.h"

#define kSCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)

#define kSCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)//應用尺寸

#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]

#define RGB(r,g,b) RGBA(r,g,b,1.0f)

#define kColorBack [UIColor groupTableViewBackgroundColor]

#define margin 15

#define kSandboxPathStr [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

#define kMp3FileName @"myRecord.mp3"

#define kCafFileName @"myRecord.caf"

2.分別遵守協議<AVAudioPlayerDelegate,AVAudioRecorderDelegate,UIGestureRecognizerDelegate>

@property (nonatomic,strong) UIView *recordView;

@property (nonatomic,strong) UIView *editView;

@property (nonatomic,strong) UIImageView *voiceView;

@property (nonatomic,strong) UILabel *timeLabel;? //錄音計時

@property (nonatomic,strong) UILabel *timeLabel2;? //語音試聽計時

@property (nonatomic,strong) UIImageView *recordBtn;

@property (nonatomic,strong) UIImageView *rotateImgView;

@property (nonatomic,strong) NSTimer *timer1;? //控制錄音時長顯示更新

@property (nonatomic,assign) NSInteger countNum;//錄音計時(秒)

@property (nonatomic,copy) NSString *cafPathStr;

@property (nonatomic,copy) NSString *mp3PathStr;

@property (nonatomic,strong) AVAudioRecorder *audioRecorder;//音頻錄音機

@property (nonatomic, strong) CABasicAnimation *rotationAnimation;

3.聲明宏定義

/**

*存放所有的音樂播放器

*/

static NSMutableDictionary *_musices;


self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

self.title = @"錄音";

self.navigationController.navigationBar.barTintColor = RGB(215, 155, 252);

[self initEditView];

[self.view addSubview:self.recordView];

self.timeLabel2.text = @"";

self.cafPathStr = [kSandboxPathStr stringByAppendingPathComponent:kCafFileName];

self.mp3PathStr =? [kSandboxPathStr stringByAppendingPathComponent:kMp3FileName];



- (void)viewWillDisappear:(BOOL)animated

{

[super viewWillDisappear:animated];

[self stopPlayRecord];

}

-(void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:animated];

[self.view endEditing:YES];

}

- (void)changeRecordTime

{

self.countNum += 1;

NSInteger min = self.countNum/60;

NSInteger sec = self.countNum - min * 60;

self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d",min,sec];

}

#pragma mark - 語音編輯視圖

- (void)initEditView{

CGFloat commonW =kSCREEN_WIDTH - margin*2;

UILabel *label1 = [[UILabel alloc]init];

label1.text = @"語音試聽";

label1.textColor = [UIColor blackColor];

label1.frame = CGRectMake(margin , margin , commonW * 0.6, 21);

label1.font = [UIFont systemFontOfSize:16];

CGFloat deleteW = 50.0;

UIView *listenView = [[UIView alloc]init];

listenView.frame = CGRectMake(margin, CGRectGetMaxY(label1.frame)+margin, commonW - deleteW - margin, 35);

listenView.layer.cornerRadius = 3;

listenView.clipsToBounds = YES;

listenView.layer.borderColor = [UIColor purpleColor].CGColor;

listenView.backgroundColor = [UIColor whiteColor];

listenView.layer.borderWidth = 1;

listenView.userInteractionEnabled = YES;

[listenView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playRecord)]];

UIImageView *iconView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"voice"]];

CGFloat iconW = 11;

CGFloat iconH = 14;

CGFloat iconX = 8;

CGFloat iconY = (listenView.frame.size.height - iconH) * 0.5;

iconView.frame = CGRectMake(iconX, iconY, iconW, iconH);

self.voiceView = iconView;

[listenView addSubview:iconView];

UILabel *timeLabel2 = [[UILabel alloc]init];

CGFloat labelW = 50;

CGFloat timeW = 120;

CGFloat timeX = listenView.frame.size.width - timeW;

timeLabel2.frame = CGRectMake(timeX, 0, timeW, listenView.frame.size.height);

timeLabel2.text = @"\"";

timeLabel2.textColor = [UIColor grayColor];

timeLabel2.textAlignment = NSTextAlignmentRight;

self.timeLabel2 = timeLabel2;

[listenView addSubview:timeLabel2];

UILabel *listenLabel = [[UILabel alloc]init];

listenLabel.frame = CGRectMake(CGRectGetMaxX(iconView.frame) + 5, 0, labelW , listenView.frame.size.height);

listenLabel.text = @"試聽";

listenLabel.textColor = [UIColor purpleColor];

[listenView addSubview:listenLabel];

UIButton *deleteBtn = [[UIButton alloc]init];

CGFloat deleteX =CGRectGetMaxX(listenView.frame) + margin;

deleteBtn.frame = CGRectMake(deleteX, CGRectGetMinY(listenView.frame), deleteW, listenView.frame.size.height);

[deleteBtn setTitle:@"刪除" forState:UIControlStateNormal];

[deleteBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

[deleteBtn setBackgroundColor:[UIColor whiteColor]];

deleteBtn.layer.cornerRadius = 3;

deleteBtn.clipsToBounds = YES;

deleteBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;

deleteBtn.layer.borderWidth = 1;

deleteBtn.titleLabel.font = [UIFont systemFontOfSize:16];

[deleteBtn addTarget:self action:@selector(showDeleteAlert) forControlEvents:UIControlEventTouchUpInside];

[self.editView addSubview:label1];

[self.editView addSubview:listenView];

[self.editView addSubview:deleteBtn];

[self pictureChangeAnimationSetting];

}

#pragma mark - 動畫效果

- (void)pictureChangeAnimationSetting

{

NSArray *picArray = @[[UIImage imageNamed:@"voice1"],

[UIImage imageNamed:@"voice2"],

[UIImage imageNamed:@"voice3"],];

//? ? self.imageView.image = [UIImage imageNamed:@"voice1"];

//imageView的動畫圖片是數組images

self.voiceView.animationImages = picArray;

//按照原始比例縮放圖片,保持縱橫比

self.voiceView.contentMode = UIViewContentModeScaleAspectFit;

//切換動作的時間3秒,來控制圖像顯示的速度有多快,

self.voiceView.animationDuration = 1;

//動畫的重復次數,想讓它無限循環就賦成0

self.voiceView.animationRepeatCount = 0;

}

#pragma mark - 刪除當前錄音

- (void)deleteCurrentRecord

{

[self deleteOldRecordFile];

[self stopPlayRecord];

self.timeLabel2.text = @"";

self.timeLabel.text = @"00:00";

}

- (void)commitVoiceNotice

{

[self audio_PCMtoMP3];

NSData *data = [NSData dataWithContentsOfFile:self.mp3PathStr];

NSString *base64Str = [self Base64StrWithMp3Data:data];

if ([self isBlankString:base64Str]) {

return;

}

NSData *mp3Data = [self Mp3DataWithBase64Str:base64Str];

//? ? [AudioTool playMusicWithData:mp3Data];

}

-(UIView *)recordView{

if (!_recordView) {

CGFloat recordH = kSCREEN_HEIGHT * 0.4;

CGFloat availH = recordH - margin * 4;

_recordView = [[UIView alloc]initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - recordH, kSCREEN_WIDTH, recordH)];

_recordView.backgroundColor = [UIColor whiteColor];

CGFloat timeH = availH * 0.2;

CGFloat btnH = availH * 0.7;

CGFloat noticeH = availH * 0.1;

self.timeLabel.frame = CGRectMake(0, margin, kSCREEN_WIDTH, timeH);

self.recordBtn.frame = CGRectMake((kSCREEN_WIDTH - btnH)*0.5, CGRectGetMaxY(self.timeLabel.frame) + margin, btnH, btnH);

self.recordBtn.layer.cornerRadius = self.recordBtn.frame.size.width * 0.5;

[self.recordBtn.layer setMasksToBounds:YES];

//? ? ? ? [self.recordBtn addTarget:self action:@selector(recordNotice) forControlEvents:UIControlEventTouchDown];

//? ? ? ? [self.recordBtn addTarget:self action:@selector(stopNotice) forControlEvents:UIControlEventTouchUpInside];

//實例化長按手勢監聽

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTableviewCellLongPressed:)];

//代理

longPress.delegate = self;

longPress.minimumPressDuration = 0.5;

[self.recordBtn addGestureRecognizer:longPress];

self.rotateImgView.frame = CGRectMake(0, 0, btnH, btnH);

self.rotateImgView.center = self.recordBtn.center;

[_recordView addSubview:self.rotateImgView];

[_recordView addSubview:self.timeLabel];

[_recordView addSubview:self.recordBtn];

UILabel *noticeLabel = [[UILabel alloc]init];

noticeLabel.frame = CGRectMake(0, recordH - noticeH - margin, kSCREEN_WIDTH, noticeH);

noticeLabel.textAlignment = NSTextAlignmentCenter;

noticeLabel.textColor = [UIColor lightGrayColor];

noticeLabel.font = [UIFont systemFontOfSize:14];

noticeLabel.text = @"按住不放錄制語音";

//? ? ? ? noticeLabel.backgroundColor = [UIColor redColor];

[_recordView addSubview:noticeLabel];

}

return _recordView;

}

//長按事件的實現方法

- (void) handleTableviewCellLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer {

if (gestureRecognizer.state ==? UIGestureRecognizerStateBegan) {

NSLog(@"UIGestureRecognizerStateBegan");

[self startRecordNotice];

}

if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {

}

if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {

NSLog(@"UIGestureRecognizerStateEnded");

[self stopRecordNotice];

}

}

#pragma mark - 錄音方法

- (void)startRecordNotice{

self.timeLabel2.text = @"";

[self stopMusicWithUrl:[NSURL URLWithString:self.cafPathStr]];

[self.voiceView.layer removeAllAnimations];

self.voiceView.image = [UIImage imageNamed:@"voice3"];

if ([self.audioRecorder isRecording]) {

[self.audioRecorder stop];

}

NSLog(@"----------開始錄音----------");

[self deleteOldRecordFile];? //如果不刪掉,會在原文件基礎上錄制;雖然不會播放原來的聲音,但是音頻長度會是錄制的最大長度。

AVAudioSession *audioSession=[AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

[_recordBtn setImage:[UIImage imageNamed:@"record_high"]];

if (![self.audioRecorder isRecording]) {//0--停止、暫停,1-錄制中

[self.audioRecorder record];//首次使用應用時如果調用record方法會詢問用戶是否允許使用麥克風

self.countNum = 0;

NSTimeInterval timeInterval =1 ; //0.1s

self.timer1 = [NSTimer scheduledTimerWithTimeInterval:timeInterval? target:self selector:@selector(changeRecordTime)? userInfo:nil? repeats:YES];

[self.timer1 fire];

}

[self starAnimalWithTime:2.0];

}

// 執行動畫

- (void)starAnimalWithTime:(CFTimeInterval)time

{

self.rotateImgView.image = [UIImage imageNamed:@"rcirle_high"];

self.rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

self.rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];

self.rotationAnimation.duration = time;

self.rotationAnimation.cumulative = YES;

self.rotationAnimation.repeatCount = HUGE_VALF;

[self.rotateImgView.layer addAnimation:self.rotationAnimation forKey:@"rotationAnimation"];

}

- (void)stopRecordNotice

{

NSLog(@"----------結束錄音----------");

[self.audioRecorder stop];

[self.timer1 invalidate];

//停止旋轉動畫

[self.rotateImgView.layer removeAllAnimations];

self.voiceView.image = [UIImage imageNamed:@"voice3"];

self.rotateImgView.image = [UIImage imageNamed:@"rcirle_norm"];

[self.recordBtn setImage:[UIImage imageNamed:@"record_norm"]];

[self audio_PCMtoMP3];

//計算文件大小

long long fileSize = [self fileSizeAtPath:self.mp3PathStr]/1024.0;

NSString *fileSizeStr = [NSString stringWithFormat:@"%lld",fileSize];

self.timeLabel2.text = [NSString stringWithFormat:@"%ld \" %@kb? ",(long)self.countNum,fileSizeStr];

self.timeLabel.text = @"00:00";

NSLog(@"timer isValid:%d",self.timer1.isValid);

//? ? NSLog(@"mp3PathStr:%@",self.mp3PathStr);

NSLog(@"countNum %d , fileSizeStr : %@",self.countNum,fileSizeStr);

}

#pragma mark - 播放

- (void)playRecord

{

[self stopAllMusic];

AVAudioSession *audioSession=[AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];? //此處需要恢復設置回放標志,否則會導致其它播放聲音也會變小

[self playMusicWithUrl:[NSURL URLWithString:self.cafPathStr]];

[self.voiceView startAnimating];

}

- (void)stopPlayRecord

{

[self stopMusicWithUrl:[NSURL URLWithString:self.cafPathStr]];

[self.voiceView.layer removeAllAnimations];

self.voiceView.image = [UIImage imageNamed:@"voice3"];

}

-(void)deleteOldRecordFile{

NSFileManager* fileManager=[NSFileManager defaultManager];

BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:self.cafPathStr];

if (!blHave) {

NSLog(@"不存在");

return ;

}else {

NSLog(@"存在");

BOOL blDele= [fileManager removeItemAtPath:self.cafPathStr error:nil];

if (blDele) {

NSLog(@"刪除成功");

}else {

NSLog(@"刪除失敗");

}

}

}

-(void)deleteOldRecordFileAtPath:(NSString *)pathStr{

NSFileManager* fileManager=[NSFileManager defaultManager];

BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:pathStr];

if (!blHave) {

NSLog(@"不存在");

return ;

}else {

NSLog(@"存在");

BOOL blDele= [fileManager removeItemAtPath:self.cafPathStr error:nil];

if (blDele) {

NSLog(@"刪除成功");

}else {

NSLog(@"刪除失敗");

}

}

}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

{

NSLog(@"delegate--播放完畢----------------------");

[self.voiceView.layer removeAllAnimations];

self.voiceView.image = [UIImage imageNamed:@"voice3"];

}

#pragma mark - caf轉mp3

- (void)audio_PCMtoMP3

{

@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 {

read = 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 {

NSLog(@"MP3生成成功: %@",self.mp3PathStr);

}

}

#pragma mark -? Getter

/**

*? 獲得錄音機對象

*

*? @return 錄音機對象

*/

-(AVAudioRecorder *)audioRecorder{

if (!_audioRecorder) {

//創建錄音文件保存路徑

NSURL *url=[NSURL URLWithString:self.cafPathStr];

//創建錄音格式設置

NSDictionary *setting=[self getAudioSetting];

//創建錄音機

NSError *error=nil;

_audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];

_audioRecorder.delegate=self;

_audioRecorder.meteringEnabled=YES;//如果要監控聲波則必須設置為YES

if (error) {

NSLog(@"創建錄音機對象時發生錯誤,錯誤信息:%@",error.localizedDescription);

return nil;

}

}

return _audioRecorder;

}

#pragma mark - AudioPlayer方法

/**

*播放音樂文件

*/

- (BOOL)playMusicWithUrl:(NSURL *)fileUrl

{

//其他播放器停止播放

[self stopAllMusic];

if (!fileUrl) return NO;

AVAudioSession *session=[AVAudioSession sharedInstance];

[session setCategory:AVAudioSessionCategoryPlayback error:nil];? //此處需要恢復設置回放標志,否則會導致其它播放聲音也會變小

[session setActive:YES error:nil];

AVAudioPlayer *player=[self musices][fileUrl];

if (!player) {

//2.2創建播放器

player=[[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];

}

player.delegate = self;

if (![player prepareToPlay]){

NSLog(@"緩沖失敗--");

//? ? ? ? [self myToast:@"播放器緩沖失敗"];

return NO;

}

[player play];

//2.4存入字典

[self musices][fileUrl]=player;

NSLog(@"musices:%@ musices",self.musices);

return YES;//正在播放,那么就返回YES

}

/**

*播放音樂文件

*/

- (void)stopMusicWithUrl:(NSURL *)fileUrl{

if (!fileUrl) return;//如果沒有傳入文件名,那么就直接返回

//1.取出對應的播放器

AVAudioPlayer *player=[self musices][fileUrl];

//2.停止

if ([player isPlaying]) {

[player stop];

NSLog(@"播放結束:%@--------",fileUrl);

}

if ([[self musices].allKeys containsObject:fileUrl]) {

[[self musices] removeObjectForKey:fileUrl];

}

}

- (BOOL)isPlayingWithUniqueID:(NSString *)uniqueID

{

if ([[self musices].allKeys containsObject:uniqueID]) {

AVAudioPlayer *player=[self musices][uniqueID];

return [player isPlaying];

}else{

return NO;

}

}

- (void)stopAllMusic

{

if ([self musices].allKeys.count > 0) {

for ( NSString *playID in [self musices].allKeys) {

AVAudioPlayer *player=[self musices][playID];

[player stop];

}

}

}

- (NSMutableDictionary *)musices

{

if (_musices==nil) {

_musices=[NSMutableDictionary dictionary];

}

return _musices;

}

/**

*? 取得錄音文件設置

*

*? @return 錄音設置

*/

-(NSDictionary *)getAudioSetting{

//LinearPCM 是iOS的一種無損編碼格式,但是體積較為龐大

//錄音設置

NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];

//錄音格式 無法使用

[recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];

//采樣率

[recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];//44100.0

//通道數

[recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];

//線性采樣位數

//[recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];

//音頻質量,采樣質量

[recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];

return recordSettings;

}

-(UIImageView *)rotateImgView

{

if (!_rotateImgView) {

_rotateImgView = [[UIImageView alloc]init];

_rotateImgView.image = [UIImage imageNamed:@"rcirle_norm"];

}

return _rotateImgView;

}

-(UIView *)editView

{

if (!_editView) {

_editView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, 200)];

_editView.backgroundColor = kColorBack;

[self.view addSubview:_editView];

}

return _editView;

}

-(UILabel *)timeLabel

{

if (!_timeLabel) {

_timeLabel = [[UILabel alloc]init];

_timeLabel.textAlignment = NSTextAlignmentCenter;

_timeLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:42];

_timeLabel.text = @"00:00";

_timeLabel.textColor = RGB(215, 155, 252);

}

return _timeLabel;

}

- (UIImageView *)recordBtn

{

if (!_recordBtn) {

_recordBtn = [[UIImageView alloc]init];

_recordBtn.backgroundColor = [UIColor clearColor];

[_recordBtn setImage:[UIImage imageNamed:@"record_norm"]];

_recordBtn.userInteractionEnabled = YES;//方便添加長按手勢

}

return _recordBtn;

}

#pragma mark - 文件轉換

// 二進制文件轉為base64的字符串

- (NSString *)Base64StrWithMp3Data:(NSData *)data{

if (!data) {

NSLog(@"Mp3Data 不能為空");

return nil;

}

//? ? NSString *str = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

NSString *str = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];

return str;

}

// base64的字符串轉化為二進制文件

- (NSData *)Mp3DataWithBase64Str:(NSString *)str{

if (str.length ==0) {

NSLog(@"Mp3DataWithBase64Str:Base64Str 不能為空");

return nil;

}

NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];

NSLog(@"Mp3DataWithBase64Str:轉換成功");

return data;

}

//單個文件的大小

- (long long) fileSizeAtPath:(NSString*)filePath{

NSFileManager* manager = [NSFileManager defaultManager];

if ([manager fileExistsAtPath:filePath]){

return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

}else{

NSLog(@"計算文件大小:文件不存在");

}

return 0;

}

- (BOOL)isBlankString:(NSString *)string {

if (string == nil || string == NULL) {

return YES;

}

if ([string isKindOfClass:[NSNull class]]) {

return YES;

}

if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {

return YES;

}

return NO;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,156評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,401評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,069評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,873評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,635評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,128評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,203評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,365評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,881評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,733評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,935評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,475評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,172評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,582評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,821評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,595評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,908評論 2 372

推薦閱讀更多精彩內容