lame,把ios錄音轉換為mp3格式


在ios設備中進行錄音,錄音文件的格式為caf。但這種格式在很多設備中沒法播放。為了適應終端的播放功能,特將caf轉換為mp3格式文件來使用。

在錄制caf文件時,需要使用雙通道,否則在轉換為MP3格式時,聲音不對。caf錄制端的設置為:

 

NSMutableDictionary * recordSetting = [NSMutableDictionary dictionary];

 

[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCMforKey:AVFormatIDKey];//

[recordSetting setValue:[NSNumber numberWithFloat:8000.0forKey:AVSampleRateKey];//采樣率

[recordSetting setValue:[NSNumber numberWithInt2forKey:AVNumberOfChannelsKey];//聲音通道,這里必須為雙通道

 [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityLowforKey:AVEncoderAudioQualityKey];//音頻質量

在轉換mp3端的代碼為:

 

NSString *cafFilePath = cafFilePathName;    //caf文件路徑

NSString *mp3FilePath = mp3FilePathName;//存儲mp3文件的路徑

    NSFileManager* fileManager=[NSFileManager defaultManager];

    if([fileManager removeItemAtPath:mp3FilePath error:nil])

    {

        NSLog(@"刪除");

    }

    

    @try {

        int read, write;

        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 轉換的音頻文件位置

        if(pcm == NULL)

        {

            NSLog(@"file not found");

        }

        else

        {

            fseek(pcm, 4*1024SEEK_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, 8000.0);//11025.0

            //lame_set_VBR(lame, vbr_default);

            lame_set_brate(lame,8);

            lame_set_mode(lame,3);

            lame_set_quality(lame,2); /* 2=high 5 = medium 7=low */

            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);

            return YES;

        }

        return NO;

    }

    @catch (NSException *exception) {

        NSLog(@"%@",[exception description]);

        return NO;

    }

    @finally {

        NSLog(@"執行完成");

    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM