Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.59/29: Рейтинг темы: голосов - 29, средняя оценка - 4.59
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
1

Микширование файлов wav

29.08.2013, 17:47. Показов 5370. Ответов 37
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Нужна помощь, нужно написать микшер, чтобы воспроизводилось два файла в формате wav. возможно кто-то писал видел, поделитесь ... А если нет, то возможно кто-то поделится идеями-советами?

На рис. приблизительно то, что я должен сделать.
Миниатюры
Микширование файлов wav  
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
29.08.2013, 17:47
Ответы с готовыми решениями:

Редактирование wav файлов
Добрый день, друзья. Подскажите, кто сможет, как в С++ именно в консольном приложении редактировать...

Считывание заголовка wav файлов
Есть код: #include <stdio.h> #include <tchar.h> #include <conio.h> #include <math.h> //...

Паузы между проигрыванием wav файлов
Добрый день ,есть загвоздка с воспроизведением звуковых файлов ,воспроизводя поочередно их...

Извлечение WAV - файлов из ресурсов и их использование
Добрый день! Сразу скажу, что тема относится к OpenAL, но подобного раздела на форуме (или хотя бы...

37
Эксперт С++
2924 / 1274 / 114
Регистрация: 27.05.2008
Сообщений: 3,465
30.08.2013, 15:27 21
Author24 — интернет-сервис помощи студентам
А про кодирование что пишет? 8 бит не могут не быть закодированными.
0
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
30.08.2013, 15:36  [ТС] 22
Все что есть...
Миниатюры
Микширование файлов wav  
0
Эксперт С++
4985 / 3092 / 456
Регистрация: 10.11.2010
Сообщений: 11,169
Записей в блоге: 10
30.08.2013, 15:39 23
Почему не могут? 22050, 8, PCM - обычный формат.
0
8 / 8 / 1
Регистрация: 11.08.2012
Сообщений: 112
30.08.2013, 15:44 24
Цитата Сообщение от Atlant_V Посмотреть сообщение
Наверно не так понял вас...
Так сама идея понятна теперь или нет?

Цитата Сообщение от CheshireCat Посмотреть сообщение
А про кодирование что пишет? 8 бит не могут не быть закодированными.
Думаю в данном случае проще всего считать заголовочную структуру файла, и посмотреть уже точно.
0
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
30.08.2013, 15:46  [ТС] 25
Цитата Сообщение от Ermak_nk Посмотреть сообщение
Так сама идея понятна теперь или нет?
понятно, только когда я предлагаю такой вариант, мне говорят, что он не подходит.
эта программа писалась не мной, поэтому я еще не разобрался в ее тонкостях. там вроде должен быть какой-то микшер уже написан и надо только организовать процесс
0
8 / 8 / 1
Регистрация: 11.08.2012
Сообщений: 112
30.08.2013, 15:50 26
Цитата Сообщение от Atlant_V Посмотреть сообщение
понятно, только когда я предлагаю такой вариант, мне говорят, что он не подходит.
Хм... в таком случае может пусть хотя бы намекнут, в какую сторону двигаться?
1
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
30.08.2013, 15:59  [ТС] 27
Спасибо за помощь) Но пока что знал с тем и остался)

Добавлено через 6 минут
Дело в том, что эта задача реализуется не только программно, но и аппаратно. Конкретно я использую декодер Barix Е200 (сомневаюсь, что это что-то кому-то скажет). Этот блок, не может принимать несколько сигналов одновременно, работает по-принципе - "кто первый, того и тапки".
0
8 / 8 / 1
Регистрация: 11.08.2012
Сообщений: 112
30.08.2013, 16:30 28
Цитата Сообщение от Atlant_V Посмотреть сообщение
Этот блок, не может принимать несколько сигналов одновременно, работает по-принципе - "кто первый, того и тапки".
Так вы на компе смешиваете 2 файла так, как описано выше, а далее посылаете одним потоком на вашу железку. Не понимаю, в чем проблема? Или эта программа пишится не для пк?
0
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
30.08.2013, 16:35  [ТС] 29
да, эта программа пишется не для пк
0
10231 / 6609 / 498
Регистрация: 28.12.2010
Сообщений: 21,156
Записей в блоге: 1
30.08.2013, 18:01 30
Назовите железо и систему.
0
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
02.09.2013, 13:59  [ТС] 31
Цитата Сообщение от raxp Посмотреть сообщение
Назовите железо и систему.
конкретно сейчас работаю с таким железом Barix E 200, потом должен усложнить добавив barix a 100. Последний должен по сети принимать звук с микрофона, передавать его на ПК, где сигнал с аналогового превращ. в цифру, потом передается на Barix e200 и пускается на колонки или гарнитуру. это так очень условно.
Вопрос про систему не понял?

Добавлено через 3 минуты
Также использую две библиотеки, emiplib i jrtplib построение через Cmake
0
10231 / 6609 / 498
Регистрация: 28.12.2010
Сообщений: 21,156
Записей в блоге: 1
02.09.2013, 14:19 32
Barix E 200
Barix Exstreamer 200.

Этими http://www.barix.com/products/... r-200-205/
?
0
0 / 0 / 0
Регистрация: 02.09.2013
Сообщений: 9
02.09.2013, 14:48 33
nero ставь там все есть и wave editor и всякие микшеры
0
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
02.09.2013, 17:12  [ТС] 34
raxp, да Этими

Добавлено через 2 минуты
Цитата Сообщение от expropriator Посмотреть сообщение
nero ставь там все есть и wave editor и всякие микшеры
если бы можно было б через nero, то я б не спрашивал именно об этом. я работаю с этими блоками не потому, что мне так захотелось, а потому что такое требование заказчика
0
8 / 8 / 1
Регистрация: 11.08.2012
Сообщений: 112
02.09.2013, 22:24 35
А для какого железа пишется микшер? Всмысле с чего на эту железку сигнал идти будет?
0
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
03.09.2013, 11:18  [ТС] 36
Цитата Сообщение от Ermak_nk Посмотреть сообщение
А для какого железа пишется микшер? Всмысле с чего на эту железку сигнал идти будет?
для тренажора, но больше ничего пока не известно.

Добавлено через 57 минут
Цитата Сообщение от Ermak_nk Посмотреть сообщение
Всмысле с чего на эту железку сигнал идти будет?
с порта ПК, это пока
0
Эксперт С++
4985 / 3092 / 456
Регистрация: 10.11.2010
Сообщений: 11,169
Записей в блоге: 10
03.09.2013, 11:33 37
Цитата Сообщение от Atlant_V Посмотреть сообщение
файлы 8 бит, используется один канал. Тот вариант s1+s2 не подходит. так как файлы могут быть разной длины. В зависимости от файла он должен играть постоянно, а другой проиграть раз.
Вообще не вижу проблемы. Просто воспроизводишь сигнал продолжительностью максимального файла, а другой подмешиваешь по кругу. 1 канал, одинаковая битность и частота дискретизации лишь упрощают этот процесс до минимума.
0
8 / 8 / 0
Регистрация: 14.08.2013
Сообщений: 99
03.09.2013, 12:19  [ТС] 38
Цитата Сообщение от castaway Посмотреть сообщение
Вообще не вижу проблемы. Просто воспроизводишь сигнал продолжительностью максимального файла, а другой подмешиваешь по кругу. 1 канал, одинаковая битность и частота дискретизации лишь упрощают этот процесс до минимума.
Спасибо, но мне сказали, что тот вариант не подходит, дали готовый вариант микшера, должен с ним разобраться.

mipaudiomixer.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#include "mipconfig.h"
#include "mipaudiomixer.h"
#include "miprawaudiomessage.h"
#include "mipsystemmessage.h"
#include "mipfeedback.h"
 
//#include <iostream> 
 
#include "mipdebug.h"
 
#define MIPAUDIOMIXER_ERRSTR_ALREADYINIT            "Already initialized"
#define MIPAUDIOMIXER_ERRSTR_NOTINIT                "Not initialized"
#define MIPAUDIOMIXER_ERRSTR_BADMESSAGE             "Bad message"
#define MIPAUDIOMIXER_ERRSTR_INCOMPATIBLESAMPRATE       "Sampling rate differs from value set during initialization"
#define MIPAUDIOMIXER_ERRSTR_INCOMPATIBLECHANNELS       "Number of channels differs from value set during initialization"
#define MIPAUDIOMIXER_ERRSTR_CANTSETPLAYBACKTIME        "Can't store playback stream time in feedback message"
#define MIPAUDIOMIXER_ERRSTR_DELAYTOOLARGE          "The specified extra delay is too large"
#define MIPAUDIOMIXER_ERRSTR_TIMINGINFOISNOTUSED        "Timing information is not being used, so the extra delay will not have any effect"
#define MIPAUDIOMIXER_ERRSTR_NEGATIVEDELAY          "Only positive delays are allowed"
 
MIPAudioMixer::MIPAudioMixer() : MIPComponent("MIPAudioMixer"), m_blockTime(0), m_playTime(0)
{
    m_init = false;
}
 
MIPAudioMixer::~MIPAudioMixer()
{
    destroy();
}
 
bool MIPAudioMixer::init(int sampRate, int channels, MIPTime blockTime, bool useTimeInfo, bool floatSamples)
{
    if (m_init)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_ALREADYINIT);
        return false;
    }
 
    m_sampRate = sampRate;
    m_channels = channels;
    m_blockTime = blockTime;
    m_blockFrames = (size_t)(blockTime.getValue()*((real_t)sampRate)+0.5);
    m_blockSize = m_blockFrames*(size_t)channels;
    m_playTime = MIPTime(0);
    m_curInterval = 0;
    m_useTimeInfo = useTimeInfo;
    m_floatSamples = floatSamples;
 
    if (floatSamples)
    {
        m_pSilenceFramesFloat = new float [m_blockSize];
        for (size_t i = 0 ; i < m_blockSize ; i++)
            m_pSilenceFramesFloat[i] = 0;
        
        m_pMsgFloat = new MIPRawFloatAudioMessage(sampRate, channels, (int)m_blockFrames, m_pSilenceFramesFloat, false);
        m_pMsgInt = 0;
        m_pSilenceFramesInt = 0;
    }
    else
    {
        m_pSilenceFramesInt = new uint16_t [m_blockSize];
        for (size_t i = 0 ; i < m_blockSize ; i++)
            m_pSilenceFramesInt[i] = 0;
        
        m_pMsgInt = new MIPRaw16bitAudioMessage(sampRate, channels, (int)m_blockFrames, true, MIPRaw16bitAudioMessage::Native, m_pSilenceFramesInt, false);
        m_pMsgFloat = 0;
        m_pSilenceFramesFloat = 0;
    }
    
    m_pBlockFramesFloat = 0;
    m_pBlockFramesInt = 0;
    
    m_extraDelay = MIPTime(0);  
    
    m_prevIteration = -1;
    m_init = true;
    
    return true;
}
 
bool MIPAudioMixer::destroy()
{
    if (!m_init)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_NOTINIT);
        return false;
    }
 
    clearAudioBlocks();
    if (m_pMsgFloat)
        delete m_pMsgFloat;
    if (m_pBlockFramesFloat)
        delete [] m_pBlockFramesFloat;
    if (m_pSilenceFramesFloat)
        delete [] m_pSilenceFramesFloat;
    if (m_pMsgInt)
        delete m_pMsgInt;
    if (m_pBlockFramesInt)
        delete [] m_pBlockFramesInt;
    if (m_pSilenceFramesInt)
        delete [] m_pSilenceFramesInt;
 
    m_init = false;
    
    return true;
}
 
bool MIPAudioMixer::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
    //std::cout << "I " << iteration << "  MIPAudioMixer::push time is " << m_playTime.getValue() << std::endl;
 
    if (!m_init)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_NOTINIT);
        return false;
    }
    
    if (pMsg->getMessageType() == MIPMESSAGE_TYPE_SYSTEM && pMsg->getMessageSubtype() == MIPSYSTEMMESSAGE_TYPE_ISTIME) // just ignore this
        return true;
    
    if (!(pMsg->getMessageType() == MIPMESSAGE_TYPE_AUDIO_RAW && ((pMsg->getMessageSubtype() == MIPRAWAUDIOMESSAGE_TYPE_FLOAT && m_floatSamples) || (!m_floatSamples && pMsg->getMessageSubtype() == MIPRAWAUDIOMESSAGE_TYPE_S16 ) )))
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_BADMESSAGE);
        return false;
    }
 
    MIPAudioMessage *pAudioMsg = (MIPAudioMessage *)pMsg;
    uint64_t sourceID = pAudioMsg->getSourceID();
 
    if (m_sourcesToIgnore.find(sourceID) != m_sourcesToIgnore.end()) 
    {
        // This source should be ignored, nothing left to do
        return true;
    }
 
    if (pAudioMsg->getSamplingRate() != m_sampRate)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_INCOMPATIBLESAMPRATE);
        return false;
    }
    if (pAudioMsg->getNumberOfChannels() != m_channels)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_INCOMPATIBLECHANNELS);
        return false;
    }
 
    real_t block = 0;
 
    if (m_useTimeInfo)
    {
        MIPTime msgTime = pAudioMsg->getTime();
        if (msgTime < m_playTime) // frames are too old to be played. Ignore
        {
            //std::cout << "           Ignoring frame! " << msgTime.getValue() << " < " << m_playTime.getValue() << std::endl << std::endl;
 
 
            return true;
        }
//      else
            //std::cout << "           Accepting message with time " << msgTime.getValue() << " >= " << m_playTime.getValue() << std::endl << std::endl;
        
        MIPTime offsetTime = msgTime;
        offsetTime -= m_playTime;
 
        if (offsetTime.getValue() > 300.0) // if it's more than five minutes in the future, ignore it
            return true;
 
        offsetTime += m_extraDelay;
        
        block = offsetTime.getValue()/m_blockTime.getValue();
    }
    else
        block = m_extraDelay.getValue()/m_blockTime.getValue();
    
    // Data is ok, process it
 
    int64_t blockOffset = (int64_t)block;
    int64_t intervalNumber = blockOffset + m_curInterval;
    real_t blockFraction = block - (real_t)blockOffset;
    size_t frameOffset = (size_t)((blockFraction * (real_t)m_blockFrames) + 0.5);
    size_t sampleOffset = frameOffset * m_channels;
    size_t numSamplesLeft = (size_t)(pAudioMsg->getNumberOfFrames())*m_channels;
    size_t samplePos = 0;
 
    if (m_floatSamples)
    {
        MIPRawFloatAudioMessage *pFloatAudioMsg = (MIPRawFloatAudioMessage *)pMsg;
        const float *pSamples = pFloatAudioMsg->getFrames();
    
        initBlockSearch();
        while (numSamplesLeft != 0)
        {
            MIPAudioMixerBlock block = searchBlock(intervalNumber);
            float *blockSamples = block.getFramesFloat();
            
            size_t num = (numSamplesLeft > (m_blockSize-sampleOffset))?(m_blockSize-sampleOffset):numSamplesLeft;
            size_t i,j,k;
            
            // add samples to the block
            for (i = 0, j = sampleOffset, k = samplePos ; i < num ; i++, j++, k++)
                blockSamples[j] += pSamples[k];
            
            sampleOffset = 0;
            samplePos += num;
            numSamplesLeft -= num;
            intervalNumber++;
        }
    }
    else // signed 16 bit
    {
        MIPRaw16bitAudioMessage *pIntAudioMsg = (MIPRaw16bitAudioMessage *)pMsg;
        const int16_t *pSamples = (const int16_t *)pIntAudioMsg->getFrames();
    
        initBlockSearch();
        while (numSamplesLeft != 0)
        {
            MIPAudioMixerBlock block = searchBlock(intervalNumber);
            int16_t *blockSamples = (int16_t *)block.getFramesInt();
            
            size_t num = (numSamplesLeft > (m_blockSize-sampleOffset))?(m_blockSize-sampleOffset):numSamplesLeft;
            size_t i,j,k;
            
            // add samples to the block
            for (i = 0, j = sampleOffset, k = samplePos ; i < num ; i++, j++, k++)
                blockSamples[j] += pSamples[k];
            
            sampleOffset = 0;
            samplePos += num;
            numSamplesLeft -= num;
            intervalNumber++;
        }
    }
    
    return true;
}
 
bool MIPAudioMixer::pull(const MIPComponentChain &chain, int64_t iteration, MIPMessage **pMsg)
{
    //std::cout << "I " << iteration << " MIPAudioMixer::pull " << m_playTime.getValue() << std::endl;
 
    if (!m_init)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_NOTINIT);
        return false;
    }
 
    if (m_floatSamples)
    {
        if (m_prevIteration !=  iteration)
        {
            m_prevIteration = iteration;
            
            // delete old frames
            if (m_pBlockFramesFloat)
                delete [] m_pBlockFramesFloat;
            m_pBlockFramesFloat = 0;
            
            if (m_audioBlocks.empty())
                m_pMsgFloat->setFrames(m_pSilenceFramesFloat,false);
            else
            {
                MIPAudioMixerBlock block = *(m_audioBlocks.begin());
    
                if (block.getInterval() == m_curInterval)
                {
                    m_audioBlocks.pop_front();
                    m_pBlockFramesFloat = block.getFramesFloat();
                    m_pMsgFloat->setFrames(m_pBlockFramesFloat,false);
                }
                else
                    m_pMsgFloat->setFrames(m_pSilenceFramesFloat,false);
            }
            
            m_gotMessage = false;
            m_curInterval++;
            m_playTime += m_blockTime;
        }
        
        if (m_gotMessage)
        {
            m_gotMessage = false;
            *pMsg = 0;
        }
        else
        {
            m_gotMessage = true;
            *pMsg = m_pMsgFloat;
        }
    }
    else // 16 bit signed
    {
        if (m_prevIteration !=  iteration)
        {
            m_prevIteration = iteration;
            
            // delete old frames
            if (m_pBlockFramesInt)
                delete [] m_pBlockFramesInt;
            m_pBlockFramesInt = 0;
            
            if (m_audioBlocks.empty())
                m_pMsgInt->setFrames(true, MIPRaw16bitAudioMessage::Native, m_pSilenceFramesInt,false);
            else
            {
                MIPAudioMixerBlock block = *(m_audioBlocks.begin());
    
                if (block.getInterval() == m_curInterval)
                {
                    m_audioBlocks.pop_front();
                    m_pBlockFramesInt = block.getFramesInt();
                    m_pMsgInt->setFrames(true, MIPRaw16bitAudioMessage::Native, m_pBlockFramesInt,false);
                }
                else
                    m_pMsgInt->setFrames(true, MIPRaw16bitAudioMessage::Native, m_pSilenceFramesInt,false);
            }
            
            m_gotMessage = false;
            m_curInterval++;
            m_playTime += m_blockTime;
        }
        
        if (m_gotMessage)
        {
            m_gotMessage = false;
            *pMsg = 0;
        }
        else
        {
            m_gotMessage = true;
            *pMsg = m_pMsgInt;
        }
    }
    //std::cout << "I " << iteration << " MIPAudioMixer::pull leaving " << m_playTime.getValue() << std::endl;
 
    return true;
}
 
void MIPAudioMixer::clearAudioBlocks()
{
    std::list<MIPAudioMixerBlock>::iterator it;
 
    for (it = m_audioBlocks.begin() ; it != m_audioBlocks.end() ; it++)
    {
        if ((*it).getFramesFloat())
            delete [] (*it).getFramesFloat();
        if ((*it).getFramesInt())
            delete [] (*it).getFramesInt();
    }
    m_audioBlocks.clear();
}
 
void MIPAudioMixer::initBlockSearch()
{
    m_it = m_audioBlocks.begin();
}
 
MIPAudioMixer::MIPAudioMixerBlock MIPAudioMixer::searchBlock(int64_t intervalNumber)
{
    if (m_it == m_audioBlocks.end())
    {
        if (m_floatSamples)
        {
            float *pNewFrames = new float [m_blockSize];
            
            memcpy(pNewFrames, m_pSilenceFramesFloat, sizeof(float)*m_blockSize);
            MIPAudioMixerBlock block(intervalNumber, pNewFrames);
            m_audioBlocks.push_back(block);
            m_it = m_audioBlocks.end();
            return block;
        }
 
        // 16 bit signed
        
        uint16_t *pNewFrames = new uint16_t [m_blockSize];
            
        memcpy(pNewFrames, m_pSilenceFramesInt, sizeof(uint16_t)*m_blockSize);
        MIPAudioMixerBlock block(intervalNumber, pNewFrames);
        m_audioBlocks.push_back(block);
        m_it = m_audioBlocks.end();
        return block;
    }
 
    if (intervalNumber < (*m_it).getInterval())
    {
        if (m_floatSamples)
        {
            float *pNewFrames = new float [m_blockSize];
            
            memcpy(pNewFrames, m_pSilenceFramesFloat, sizeof(float)*m_blockSize);
            MIPAudioMixerBlock block(intervalNumber, pNewFrames);
            m_it = m_audioBlocks.insert(m_it, block);
            m_it++;
            return block;
        }
 
        // 16 bit signed        
        
        uint16_t *pNewFrames = new uint16_t [m_blockSize];
            
        memcpy(pNewFrames, m_pSilenceFramesInt, sizeof(uint16_t)*m_blockSize);
        MIPAudioMixerBlock block(intervalNumber, pNewFrames);
        m_it = m_audioBlocks.insert(m_it, block);
        m_it++;
        return block;
    }
 
    if (intervalNumber == (*m_it).getInterval())
    {
        MIPAudioMixerBlock block = (*m_it);
        m_it++;
        return block;
    }
 
    // intervalNumber > (*m_it).getInterval()
    
    bool done = false;
    
    while (!done)
    {
        m_it++;
        if (m_it == m_audioBlocks.end())
        {
            done = true;
        }
        else
        {
            if ((*m_it).getInterval() == intervalNumber)
            {
                MIPAudioMixerBlock block = (*m_it);
                m_it++;
                return block;
            }
 
            if (intervalNumber < (*m_it).getInterval())
            {
                if (m_floatSamples)
                {
                    float *pNewFrames = new float [m_blockSize];
            
                    memcpy(pNewFrames, m_pSilenceFramesFloat, sizeof(float)*m_blockSize);
                    MIPAudioMixerBlock block(intervalNumber, pNewFrames);
                    m_it = m_audioBlocks.insert(m_it, block);
                    m_it++;
                    return block;
                }
 
                // 16 bit signed
                
                uint16_t *pNewFrames = new uint16_t [m_blockSize];
            
                memcpy(pNewFrames, m_pSilenceFramesInt, sizeof(uint16_t)*m_blockSize);
                MIPAudioMixerBlock block(intervalNumber, pNewFrames);
                m_it = m_audioBlocks.insert(m_it, block);
                m_it++;
                return block;
            }
        }
    } 
    
    if (m_floatSamples)
    {
        float *pNewFrames = new float [m_blockSize];
            
        memcpy(pNewFrames, m_pSilenceFramesFloat, sizeof(float)*m_blockSize);
        MIPAudioMixerBlock block(intervalNumber, pNewFrames);
        m_audioBlocks.push_back(block);
        m_it = m_audioBlocks.end();
        return block;
    }
 
    // 16 bit signed
    
    uint16_t *pNewFrames = new uint16_t [m_blockSize];
            
    memcpy(pNewFrames, m_pSilenceFramesInt, sizeof(uint16_t)*m_blockSize);
    MIPAudioMixerBlock block(intervalNumber, pNewFrames);
    m_audioBlocks.push_back(block);
    m_it = m_audioBlocks.end();
    return block;
}
 
bool MIPAudioMixer::processFeedback(const MIPComponentChain &chain, int64_t feedbackChainID, 
                                    MIPFeedback *feedback)
{
    if (!m_init)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_NOTINIT);
        return false;
    }
    if (!feedback->setPlaybackStreamTime(m_playTime))
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_CANTSETPLAYBACKTIME);
        return false;
    }
    feedback->addToPlaybackDelay(m_extraDelay);
    return true;
}
 
bool MIPAudioMixer::setExtraDelay(MIPTime t)
{
    if (t.getValue() < 0)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_NEGATIVEDELAY);
        return false;
    }
 
    if (t.getValue() > 300.0)
    {
        setErrorString(MIPAUDIOMIXER_ERRSTR_DELAYTOOLARGE);
        return false;
    }
    
    m_extraDelay = t;
    return true;
}
Добавлено через 21 минуту
mipaudiomixer.h
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#ifndef MIPAUDIOMIXER_H
 
#define MIPAUDIOMIXER_H
 
#include "mipconfig.h"
#include "mipcomponent.h"
#include "miptime.h"
#include <list>
#include <set>
 
class MIPRaw16bitAudioMessage;
class MIPRawFloatAudioMessage;
 
/** This component can mix several audio streams.
 *  Using this component, several audio streams can be mixed. In the default mode, it accepts 
 *  floating point raw audio messages and produces floating point raw audio messages. You
 *  can also work with signed 16 bit native raw audio messages. This component
 *  generates feedback about the current offset in the output stream.
 */
class EMIPLIB_IMPORTEXPORT MIPAudioMixer : public MIPComponent
{
public:
    MIPAudioMixer();
    ~MIPAudioMixer();
 
    /** Initializes the mixer component.
     *  Using this function, the audio mixer component can be initialized.
     *  \param sampRate The sampling rate of incoming and outgoing audio messages.
     *  \param channels The number of channels of incoming and outgoing audio messages.
     *  \param blockTime Audio messages created by this component contain the amount of
     *                   data corresponding to the specified time interval in \c blockTime
     *  \param useTimeInfo If set to \c true, the time information in a raw audio message
     *                     will be used to determine the position of the audio in the output
     *                     stream. If set to \c false, incoming messages will be inserted
     *                     at the head of the stream and timing information will be ignored.
     *  \param floatSamples Flag indicating if floating point samples should be used or
     *                      signed 16 bit native endian samples.
     */
    bool init(int sampRate, int channels, MIPTime blockTime, bool useTimeInfo = true, bool floatSamples = true);
 
    /** De-initializes the mixer component.
     *  This function frees the resources claimed by the mixer component.
     */
    bool destroy();
 
    /** Adds an additional playback delay.
     *  Using this function, an additional playback delay can be introduced. Note that only
     *  positive delays are allowed. This can be useful for inter-media synchronization, in
     *  case not all the component delays are known well enough to provide exact synchronization.
     *  Using this function, the synchronization can then be adjusted manually.
     */
    bool setExtraDelay(MIPTime t);
 
    /** Sets the internal playback time to a specific value.
     *  Sets the internal playback time to a specific value. This allows multiple
     *  audio mixers to be nicely synchronized (can come in handy when creating an
     *  audio mixing server).
     */
    void setPlaybackTime(MIPTime t)                             { m_playTime = t; }
 
    /** Returns the current internal playback time of this mixer. */
    MIPTime getPlaybackTime() const                             { return m_playTime; }
 
    /** Adds a source identifier which should be ignored. */
    void addSourceToIgnore(uint64_t id)                         { m_sourcesToIgnore.insert(id); }
 
    /** Clears the list of sources to ignore. */
    void clearIgnoreList()                                  { m_sourcesToIgnore.clear(); }
    
    bool push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg);
    bool pull(const MIPComponentChain &chain, int64_t iteration, MIPMessage **pMsg);
    bool processFeedback(const MIPComponentChain &chain, int64_t feedbackChainID, MIPFeedback *feedback);
private:
    class MIPAudioMixerBlock
    {
    public:
        MIPAudioMixerBlock(int64_t playInterval, float *pFrames)            { m_interval = playInterval; m_pFloatFrames = pFrames; m_pIntFrames = 0; }
        MIPAudioMixerBlock(int64_t playInterval, uint16_t *pFrames)         { m_interval = playInterval; m_pFloatFrames = 0; m_pIntFrames = pFrames; }
        float *getFramesFloat()                             { return m_pFloatFrames; }
        uint16_t *getFramesInt()                            { return m_pIntFrames; }
        int64_t getInterval() const                         { return m_interval; }
    private:
        float *m_pFloatFrames;
        uint16_t *m_pIntFrames;
        int64_t m_interval;
    };
    
    void clearAudioBlocks();
    void initBlockSearch();
    MIPAudioMixerBlock searchBlock(int64_t intervalNumber);
    
    bool m_init;
    bool m_useTimeInfo;
    int64_t m_prevIteration;
    bool m_gotMessage;
    bool m_floatSamples;
 
    MIPTime m_blockTime, m_playTime;
    int m_sampRate, m_channels;
    size_t m_blockFrames,m_blockSize;
    int64_t m_curInterval;
    
    MIPRawFloatAudioMessage *m_pMsgFloat;
    MIPRaw16bitAudioMessage *m_pMsgInt;
    float *m_pSilenceFramesFloat;
    uint16_t *m_pSilenceFramesInt;
    float *m_pBlockFramesFloat;
    uint16_t *m_pBlockFramesInt;
 
    MIPTime m_extraDelay;
    
    std::list<MIPAudioMixerBlock> m_audioBlocks;
    std::list<MIPAudioMixerBlock>::iterator m_it;
 
    std::set<uint64_t> m_sourcesToIgnore;
};
 
#endif // MIPAUDIOMIXER_H


Добавлено через 9 секунд
mipaudiomixer.h
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#ifndef MIPAUDIOMIXER_H
 
#define MIPAUDIOMIXER_H
 
#include "mipconfig.h"
#include "mipcomponent.h"
#include "miptime.h"
#include <list>
#include <set>
 
class MIPRaw16bitAudioMessage;
class MIPRawFloatAudioMessage;
 
/** This component can mix several audio streams.
 *  Using this component, several audio streams can be mixed. In the default mode, it accepts 
 *  floating point raw audio messages and produces floating point raw audio messages. You
 *  can also work with signed 16 bit native raw audio messages. This component
 *  generates feedback about the current offset in the output stream.
 */
class EMIPLIB_IMPORTEXPORT MIPAudioMixer : public MIPComponent
{
public:
    MIPAudioMixer();
    ~MIPAudioMixer();
 
    /** Initializes the mixer component.
     *  Using this function, the audio mixer component can be initialized.
     *  \param sampRate The sampling rate of incoming and outgoing audio messages.
     *  \param channels The number of channels of incoming and outgoing audio messages.
     *  \param blockTime Audio messages created by this component contain the amount of
     *                   data corresponding to the specified time interval in \c blockTime
     *  \param useTimeInfo If set to \c true, the time information in a raw audio message
     *                     will be used to determine the position of the audio in the output
     *                     stream. If set to \c false, incoming messages will be inserted
     *                     at the head of the stream and timing information will be ignored.
     *  \param floatSamples Flag indicating if floating point samples should be used or
     *                      signed 16 bit native endian samples.
     */
    bool init(int sampRate, int channels, MIPTime blockTime, bool useTimeInfo = true, bool floatSamples = true);
 
    /** De-initializes the mixer component.
     *  This function frees the resources claimed by the mixer component.
     */
    bool destroy();
 
    /** Adds an additional playback delay.
     *  Using this function, an additional playback delay can be introduced. Note that only
     *  positive delays are allowed. This can be useful for inter-media synchronization, in
     *  case not all the component delays are known well enough to provide exact synchronization.
     *  Using this function, the synchronization can then be adjusted manually.
     */
    bool setExtraDelay(MIPTime t);
 
    /** Sets the internal playback time to a specific value.
     *  Sets the internal playback time to a specific value. This allows multiple
     *  audio mixers to be nicely synchronized (can come in handy when creating an
     *  audio mixing server).
     */
    void setPlaybackTime(MIPTime t)                             { m_playTime = t; }
 
    /** Returns the current internal playback time of this mixer. */
    MIPTime getPlaybackTime() const                             { return m_playTime; }
 
    /** Adds a source identifier which should be ignored. */
    void addSourceToIgnore(uint64_t id)                         { m_sourcesToIgnore.insert(id); }
 
    /** Clears the list of sources to ignore. */
    void clearIgnoreList()                                  { m_sourcesToIgnore.clear(); }
    
    bool push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg);
    bool pull(const MIPComponentChain &chain, int64_t iteration, MIPMessage **pMsg);
    bool processFeedback(const MIPComponentChain &chain, int64_t feedbackChainID, MIPFeedback *feedback);
private:
    class MIPAudioMixerBlock
    {
    public:
        MIPAudioMixerBlock(int64_t playInterval, float *pFrames)            { m_interval = playInterval; m_pFloatFrames = pFrames; m_pIntFrames = 0; }
        MIPAudioMixerBlock(int64_t playInterval, uint16_t *pFrames)         { m_interval = playInterval; m_pFloatFrames = 0; m_pIntFrames = pFrames; }
        float *getFramesFloat()                             { return m_pFloatFrames; }
        uint16_t *getFramesInt()                            { return m_pIntFrames; }
        int64_t getInterval() const                         { return m_interval; }
    private:
        float *m_pFloatFrames;
        uint16_t *m_pIntFrames;
        int64_t m_interval;
    };
    
    void clearAudioBlocks();
    void initBlockSearch();
    MIPAudioMixerBlock searchBlock(int64_t intervalNumber);
    
    bool m_init;
    bool m_useTimeInfo;
    int64_t m_prevIteration;
    bool m_gotMessage;
    bool m_floatSamples;
 
    MIPTime m_blockTime, m_playTime;
    int m_sampRate, m_channels;
    size_t m_blockFrames,m_blockSize;
    int64_t m_curInterval;
    
    MIPRawFloatAudioMessage *m_pMsgFloat;
    MIPRaw16bitAudioMessage *m_pMsgInt;
    float *m_pSilenceFramesFloat;
    uint16_t *m_pSilenceFramesInt;
    float *m_pBlockFramesFloat;
    uint16_t *m_pBlockFramesInt;
 
    MIPTime m_extraDelay;
    
    std::list<MIPAudioMixerBlock> m_audioBlocks;
    std::list<MIPAudioMixerBlock>::iterator m_it;
 
    std::set<uint64_t> m_sourcesToIgnore;
};
 
#endif // MIPAUDIOMIXER_H
0
03.09.2013, 12:19
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
03.09.2013, 12:19
Помогаю со студенческими работами здесь

Фоновая программа для проигрывания wav-файлов
Всем привет;))) Решил тут запилить совсем простенькую программку на проигрывание .wav файла, чтобы...

Прога преобразования wav файлов в data или txt
Такой вопрос, может быть кто-нибудь писал прогу для перезаписи wav файлов в data или txt, чтобы в...

Ребята дайте код для воспроизведения файлов wav или mp3
Привет всем! Дайте код для воспроизведения mp3 или wav файла! Буду благодарен)

Написать программу, формирующую по исходному WAV файлу новый WAV файл
Написать программу, формирующую по исходному WAV файлу новый WAV файл, со сглаженным вершинами...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
38
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru