K
K
Kirill Zhilyaev2020-05-19 13:01:35
Qt
Kirill Zhilyaev, 2020-05-19 13:01:35

How to compress an audio stream through Opus?

I'm writing some kind of voice chat. There is this code:

voip::voip(QWidget *parent)
  : QWidget(parent)
{
  ui.setupUi(this);

  QAudioFormat format;
  format.setSampleRate( 48000 );
  format.setChannelCount( 2 );
  format.setSampleSize( 8 );
  format.setCodec( "audio/pcm" );
  format.setByteOrder( QAudioFormat::LittleEndian );
  format.setSampleType( QAudioFormat::SignedInt );

  QAudioDeviceInfo info( QAudioDeviceInfo::defaultOutputDevice( ) );


  QAudioOutput *out = new QAudioOutput( format, this );
  QAudioInput *in = new QAudioInput( format, this );
  in->setNotifyInterval( 20 );

  QIODevice * inIO = in->start( );

  QIODevice * outIO = out->start( );

  int error = 0;

  OpusEncoder *encoder =  opus_encoder_create( 48000, 2, OPUS_APPLICATION_VOIP, &error );
  opus_encoder_ctl( encoder, OPUS_SET_BITRATE( 64000 ) );

  OpusDecoder *decoder = opus_decoder_create( 48000, 2, &error );
  opus_decoder_ctl( decoder, OPUS_SET_BITRATE( 64000 ) );

  connect( in, &QAudioInput::notify, this, [=] {
    QByteArray ba = inIO->readAll( );

    unsigned char *data = new unsigned char[1440];
    opus_int16 *pcm = new opus_int16[1440 * 2];

    int nbBytes = opus_encode( encoder, (opus_int16 *)inIO->readAll( ).data( ), 960, data, 1440 );
    
    // Тип приняли данные

    int nbBytes2 = opus_decode( decoder, data, nbBytes, pcm, 1440, 0);

    outIO->write( (char *)pcm, nbBytes2 * 2 );
    
  } );
}


But after opus_decode I get noise. Is there a way to fix it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question