2017-07-28 132 views
0

我試圖使用Samplerate 16000從wav文件轉換爲mp3。轉換後的音頻質量不好,其速度似乎增加了。凡爲它的工作好,如果設置爲8000音頻轉換採樣率,我創建了方法,WAV到MP3:如何將wav轉換爲採樣率16000的mp3?

+(void)convertFromWavToMp3:(NSString *)filePath FileName:(NSString *)kFileName SampleRate:(int)kSampleRate failAction:(WavToMp3CompletionBlock)failBlock successAction:(WavToMp3CompletionBlock)successBlock 

{

NSLog(@"%@", [filePath stringByDeletingLastPathComponent]); 

NSString *mp3FileName = kFileName; 
mp3FileName = [mp3FileName stringByAppendingString:@".mp3"]; 
NSString *mp3FilePath = [[filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:mp3FileName]; 

NSLog(@"%@", mp3FilePath); 

@try { 
    int read, write; 

    NSFileManager *filemgr; 
    filemgr = [NSFileManager defaultManager]; 
    char const *path_cstr = [filemgr fileSystemRepresentationWithPath:filePath]; 

    FILE *pcm = fopen(path_cstr, "rb"); //source 
    fseek(pcm, 4*1024, SEEK_CUR);         //skip file header 
    FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 

    const int PCM_SIZE = 16384; 
    const int MP3_SIZE = 16384; 
    short int pcm_buffer[PCM_SIZE*2]; 
    unsigned char mp3_buffer[MP3_SIZE]; 

    lame_t lame = lame_init(); 
    lame_set_in_samplerate(lame, 8000); 
    lame_set_num_channels(lame, 1); 
    lame_set_VBR(lame, vbr_default); 
    // lame_set_brate(lame, 128); 

    lame_set_quality(lame, 0); 
    lame_set_brate(lame, 128); 

    lame_set_num_samples(lame, 8000); 
    lame_set_out_samplerate(lame, 8000); 
    lame_set_mode(lame, 3); 

    lame_init_params(lame); 

    lame_print_config(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); 
    successBlock(true); 
} 
@catch (NSException *exception) { 
    NSLog(@"%@",[exception description]); 
    failBlock(false); 
} 
@finally { 

} 
+0

請檢查我的答案。 –

+0

我的回答對你有幫助嗎? –

回答

1

用於轉換波到MP3的使用可以使用ExtAudioFileConverter類: https://github.com/lixing123/ExtAudioFileConverter

用於轉換的mp3採樣率16000:

ExtAudioConverter* converter = [[ExtAudioConverter alloc] init]; 
converter.outputSampleRate = 16000; 
converter.outputNumberChannels = 2; 
converter.outputBitDepth = BitDepth_16; 
converter.outputFormatID = kAudioFormatLinearPCM; 
converter.outputFileType = kAudioFileMP3Type; 

converter.inputFile = @"Desktop/input.wav"; 
converter.outputFile = @"Desktop/output.mp3"; 
[converter convert];