QtMultimedia,如何以mp3,wav或smth等任何格式保存录音?

时间:2011-01-27 00:44:49

标签: c++ qt

嗯,像我在教程中看到的那样,但是我想保存一种可读的音乐播放器格式。有可能吗?

file   = new QFile("smth.raw");
file->open(QIODevice::WriteOnly | QIODevice::Truncate );

QAudioFormat format;
format.setFrequency(8000);
format.setChannels(1);
format.setSampleSize(8);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
if (!info.isFormatSupported(format)) {
    qWarning()<<"default format not supported try to use nearest";
    format = info.nearestFormat(format);
}
audioInput = new QAudioInput(format, this);

1 个答案:

答案 0 :(得分:3)

好吧,如果它对某人有意思,那就是要转换的算法。如果您有更好的想法,请回复!

 #include <stdio.h>
 int rawToWav(const char *rawfn, const char *wavfn, long frequency)
 {
    long chunksize=0x10;

    struct
    {
        unsigned short    wFormatTag;
        unsigned short    wChannels;
        unsigned long     dwSamplesPerSec;
        unsigned long     dwAvgBytesPerSec;
        unsigned short    wBlockAlign;
        unsigned short    wBitsPerSample;
    } fmt;

    FILE *raw = fopen(rawfn,"rb");
    if(!raw)
        return -2;

    fseek(raw, 0, SEEK_END);
    long bytes = ftell(raw);
    fseek(raw, 0, SEEK_SET);

    long samplecount = bytes/2;
    long riffsize    = samplecount*2+0x24;
    long datasize    = samplecount*2;

    FILE *wav=fopen(wavfn,"wb");
    if(!wav)
    {
        fclose(raw);
        return -3;
    }

    fwrite( "RIFF",     1, 4, wav );
    fwrite( &riffsize,  4, 1, wav );
    fwrite( "WAVEfmt ", 1, 8, wav );
    fwrite( &chunksize, 4, 1, wav );

    fmt.wFormatTag = 1;      // PCM
    fmt.wChannels  = 1;      // MONO
    fmt.dwSamplesPerSec  = frequency*1;
    fmt.dwAvgBytesPerSec = frequency*1*2; // 16 bit
    fmt.wBlockAlign      = 2;
    fmt.wBitsPerSample   = 16;

    fwrite( &fmt,      sizeof(fmt), 1, wav );
    fwrite( "data",    1,           4, wav );
    fwrite( &datasize, 4,           1, wav );
    short buff[1024];
    while( !feof(raw) )
    {
          int cnt=fread(buff,2,1024,raw);
          if( cnt == 0 )
              break;
          fwrite(buff,2,cnt,wav);
    }
    fclose( raw );
    fclose( wav );
}