Дмитрий
ДмитрийFeb. 28, 2019, 9:14 a.m.

Opening mp3 files using the audiere library

The audiere library allows you to work with audio files of various formats (wav, mp3, etc.). To work, we need the files audiere.h, audiere.lib, audiere.dll. h-file is included in the program code

#include "audiere.h"

lib-file is linked to .pro

LIBS += audiere.lib

dll we drag behind the program.
In RuNet it is easy to find information on how to play sound with it. But there is absolutely no information on how to get audio data for further processing. Therefore, I will write, especially since it is quite simple.


1 open file

    QString name = "D:/qtProg/audioprocessor/test2.mp3"; 
    name.replace("/","\\");
    SampleSourcePtr source;
    source = OpenSampleSource( name.toLocal8Bit() ); 
    if(!source)
    {
        ui->statusBar->showMessage("файл не открыт");
        return;
    }
    else
    {
        ui->statusBar->showMessage(name);
    }

2 read audio parameters

    int ccount; // число каналов
    int samplerate; // частота дискретизации
    SampleFormat format; // формат данных

    source->getFormat(ccount, samplerate, format);
    int l = source->getLength(); // число отсчётов одного канала

For typical audio recordings, the number of channels is two, single-channel recordings are quite common, I have not seen others, but it should work on the same principle. Note that the number of samples obtained with getLength() corresponds to one channel. Sampling frequency (if you don't know what it is, check out the Kotelnikov theorem or the Nyquist theorem). Format - determines the number of bits that encode one sample (usually 16).

3 create buffer and suitable storage

    int w = 256; // размер временного окна
    qint16 buf[w*ccount];

    QVector<qint16> data; // хранилище данных для одного канала

4 read data

    int row = l/w; // число временных фрагментов

    for(int j = 0; j < row; j++)
    {
        source->read(w, buf); // считывание фрагмента
        for(int i=0; i<w; i++)
        {
            data.append(buf[i*ccount]);
        }
    }
    source->read(w, buf); // считывание последнего фрагмента
    for(int i=0; i < l%w; i++)
    {
        data.append(buf[i*ccount]);
    }

Now the extracted data can be processed...
The text of the program can be downloaded here

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Evgenii Legotckoi
  • Feb. 28, 2019, 2:27 p.m.
  • (edited)

Добрый день, Дмитрий.

Спасибо за статью. Единственный момент, пожалуйста, поместите статью под кат, то есть отделите большую часть статьи разделителем контента, это одна из кнопок в тулбаре редактора. Она отделяет превью статьи в ленте от остальной части контента.

Ещё раз спасибо.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
СЦ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
AT

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
m

C++ - Test 002. Constants

  • Result:58points,
  • Rating points-2
Last comments
АН
Алексей НиколаевMarch 26, 2023, 9:10 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Добрый день, взял за основу ваш PopUp notification , и немного доработал его под свои нужды. Добавил в отдельном eventloop'e всплывающую очередь уведомлений с анимацией и таймеро…
АН
Алексей НиколаевMarch 26, 2023, 9:04 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Включите прозрачность в композит менеджере fly-admin-theme : fly-admin-theme ->Эффекты и всё заработает.
NSProject
NSProjectMarch 24, 2023, 2:35 p.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Да не я так к примеру просто написал.
Evgenii Legotckoi
Evgenii LegotckoiMarch 24, 2023, 10:09 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Почитайте эту статью про "хлебные крошки"
NSProject
NSProjectMarch 24, 2023, 9:15 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Хорошая статья. И тут я подумал что на её основе можно отлично сформировать "хлебные крошки". Самое простое распарсить адрес. Так и поступил бы но лень
Now discuss on the forum
P
PisychMarch 29, 2023, 5:35 a.m.
Как подсчитать количество по условию? большое спасибо. завтра проверю. сейчас уже нет возможности:(
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 4:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
ВА
Виталий АнисимовJan. 29, 2023, 3:17 p.m.
Как добавить виртуальную клавиатура с Т9 в своей проект на QML. Добрый день. Прошу помочь, пишу небольше приложение в Qt. Добвил в свой проект виртуальную клавиатуру от Qt. Но как добавить в него возможность изменения Т9 никак не могу понять.
P
PisychMarch 16, 2023, 12:23 a.m.
Как записать значение даты в Input date? Уппс! нашел ошибку. Тема закрыта
Evgenii Legotckoi
Evgenii LegotckoiMarch 15, 2023, 5:08 a.m.
Почему не работает редирект? Добрый день! Через Ajax редирект и не будет работать. Вам нужно вернуть JsonResponse и обработать его в на клиентской стороне в скрипте вызов Ajax. То есть вызвать редирект в этой фун…

Follow us in social networks