symba (779893), страница 25

Файл №779893 symba (Symbian Books) 25 страницаsymba (779893) страница 252018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 25)

The headerdeclares the main class CIOStreamAudio and its observer MAudioIOStreamObserver.class MAudioIOStreamObserver{public:// Signal recording has stopped - for infovirtual void RecordingStopped() = 0;// Signal completion of test with associated errorvirtual void PlayOrRecordComplete(TInt aError) = 0;};class CIOStreamAudio : public CBase,public MMdaAudioInputStreamCallback,public MMdaAudioOutputStreamCallback{AUDIO INPUT AND OUTPUT STREAMSenum TState{EStateIdle,EStateOpeningInput,EStateReading,EStateOpeningOutput,EStateWriting,EStateWritingPostBuffer};public:static CIOStreamAudio* NewL(MAudioIOStreamObserver* aObserver);∼CIOStreamAudio();public:void RecordL(TInt aBufferSize);void StopAndPlay();public:// from MMdaAudioInputStreamCallbackvoid MaiscOpenComplete(TInt aError);void MaiscBufferCopied(TInt aError, const TDesC8& aBuffer);void MaiscRecordComplete(TInt aError);// from MMdaAudioOutputStreamCallbackvoid MaoscOpenComplete(TInt aError);void MaoscBufferCopied(TInt aError, const TDesC8& aBuffer);void MaoscPlayComplete(TInt aError);protected:CIOStreamAudio(MAudioIOStreamObserver* aObserver);void ConstructL();void OnOpenL();void ReadNextBlock(const TDesC8& aBuffer);void WriteNextBlockL(const TDesC8& aBuffer);void Complete(TInt aError);private:MAudioIOStreamObserver*const iObserver;TState iState;RBuf8 iMainBuffer;CMdaAudioInputStream* iInputStream;CMdaAudioOutputStream* iOutputStream;TPtr8 iBufferPtr;};CIOStreamAudio* CIOStreamAudio::NewL(MAudioIOStreamObserver* aObserver){CIOStreamAudio* self = new(ELeave) CIOStreamAudio(aObserver);CleanupStack::PushL(self);self->ConstructL();CleanupStack::Pop(self);return self;}CIOStreamAudio::∼CIOStreamAudio(){if (iInputStream){iInputStream->Stop();delete iInputStream;}if (iOutputStream){109110MULTIMEDIA FRAMEWORK: AUDIOiOutputStream->Stop();delete iOutputStream;}iMainBuffer.Close();}void CIOStreamAudio::ConstructL(){iInputStream = CMdaAudioInputStream::NewL(*this);iOutputStream = CMdaAudioOutputStream::NewL(*this);}CIOStreamAudio::CIOStreamAudio(MAudioIOStreamObserver* aObserver) :iObserver(aObserver),iBufferPtr(NULL, 0){}void CIOStreamAudio::Complete(TInt aError){iState = EStateIdle;iObserver->PlayOrRecordComplete(aError);}This code follows the usual Symbian coding idioms.

Notice how in thedestructor, both iInputStream and iOutputStream are stoppedprior to deletion (if they are not playing this does no harm) and thecode first checks the pointers are not NULL. It is very important to dothis since the pointers may be NULL in some low-memory scenarios.5.2.2 Stream Calls for RecordingLike most of the audio APIs, CMdaAudioInputStream operates intwo phases: initialization and the action itself. The key operations areshown below: RecordL() is called by the application and the MaiscOpenComplete() callback is called from CMdaAudioInputStreamitself.void CIOStreamAudio::RecordL(TInt aBufferSize){// if buffer is already allocated, throw away and re-createiMainBuffer.Close();User::LeaveIfError(iMainBuffer.Create(aBufferSize));iInputStream->Open(NULL); // use default settingsiState = EStateOpeningInput;}The RecordL() operation initializes iMainBuffer (where we storethe recorded data) and opens the input stream.

Technically initializationAUDIO INPUT AND OUTPUT STREAMS111of the main buffer could be delayed until first use, which follows below,but doing it here is easier to drive from your client code – usually theleave happens when you are handling a key-click or screen event andit is simpler to relay it back to the user. The key thing, though, is thecall to CMdaAudioInputStream::Open(). This is asynchronous – itgenerates a MaiscOpenComplete() callback asynchronously, afterOpen() has returned. We now almost always use NULL as the parameter;originally, if you wanted to override settings such as sample rate andformat, this is where you did it, but the API has evolved and now wedo this a bit later in the sequence. You’ll probably notice the states inthis scenario – these are purely to do with the example code and itsasynchronous nature.Following the Open() call, you get a MaiscOpenComplete() callback:void CIOStreamAudio::MaiscOpenComplete(TInt aError){ASSERT(iState == EStateOpeningInput);if (aError != KErrNone){Complete(aError);}else{iMainBuffer.Zero();iState = EStateReading;ReadNextBlock(KNullDesC8); // kick off a new read –}// KNullDesC8 for first buffer}If the error code is not KErrNone, opening failed for some reasonand we send a failure callback to the application via Complete().Otherwise, we reset the main buffer via Zero() and start to read viaReadNextBlock() – note the trick of supplying KNullDesC8 to statethat nothing was read in the ‘previous iteration’, which is definitely truesince this is the first! It is perhaps worth noting the use of KNullDesC8,instead of KNullDesC.

Essentially, where the audio APIs use descriptorsto pass data back and forth, we almost always use eight-bit descriptorsnot (standard) 16-bit ones. This should make sense – you use eight-bitdescriptors for binary data.Next let’s look at ReadNextBlock():void CIOStreamAudio::ReadNextBlock(const TDesC8& aBuffer){ASSERT(iState == EStateReading);// buffer is tail of iMainBuffer. Shift length of// iMainBuffer and get the next bitTInt lengthRecorded = iMainBuffer.Length() + aBuffer.Length();112MULTIMEDIA FRAMEWORK: AUDIOiMainBuffer.SetLength(lengthRecorded);iBufferPtr.Set(const_cast<TUint8*> (iMainBuffer.Ptr()) + lengthRecorded,0, iMainBuffer.MaxLength() - lengthRecorded);TRAPD(error, iInputStream->ReadL(iBufferPtr));if (error != KErrNone){Complete(error);}}We need to point out that there are actually two buffers mentionedby this class: iMainBuffer is the whole recorded length of data andiBufferPtr is used as a running ‘save here’ reference.

In its standarduse, this program is used to record two seconds of data via a timer inthe application and the aBuffer size parameter is set to always be largeenough – the default of 8000 samples per second, 16 bits per sample andmono works out to be 16 KB/s, so 40 KB should be ample. So we wantto record into a large descriptor. However, by default, audio recordingworks by generating lots of short buffers, and if you ask for too much datait actually returns only so much each time.

Typically this data is 4–16 KB,but it could be larger and could even be smaller. The thing to do is notto write your application assuming the size of the underlying low-levelbuffers.ReadNextBlock() works by arranging for iBufferPtr to point tothe rest of iMainBuffer – that is the part of iMainBuffer that has notyet been recorded to. In the next iteration, the length of iMainBufferis updated to include newly recorded data and iBufferPtr is updatedto point to what is now the unrecorded section.This example ignores the problem of the buffer being too small, butit should really just stop recording if there is insufficient space in thebuffer – you are free to update the code to handle that.The call to request a new buffer of data is CMdaAudioInputStream::ReadL(), which generates a subsequent, asynchronousMaiscBufferCopied() callback.

Basically if you get an error, apartfrom KErrAbort, you stop processing and tell the main client. Otherwise, you keep processing – in this program calling ReadNextBlock().void CIOStreamAudio::MaiscBufferCopied(TInt aError, const TDesC8& aBuffer){ASSERT(iState == EStateReading);if (aError != KErrNone){AUDIO INPUT AND OUTPUT STREAMS113if (aError != KErrAbort) // aborts happen on Stop as buffers are// recovered; need to ignore{iInputStream->Stop();Complete(aError);}}else{ReadNextBlock(aBuffer);}}It is perhaps worth noting that the API itself supports double or quadruple buffering – you can fire off several ReadL() calls and they willbe responded to sequentially with separate MaiscBuffer-Copied()calls.

Thus if you have buffers buffer1 and buffer2, you can doReadL(buffer1) immediately followed by ReadL(buffer2). Thesystem adds data to buffer1 and calls MaiscBufferCopied() forbuffer1; it then adds data to buffer2 and calls MaiscBufferCopied() for buffer2; the aBuffer parameter says what the associated buffer is, as well as giving the length of the data actually read. Asyou’re probably guessing, there is an internal FIFO queue to implementthis.You can use this, but do you have to? Our experience says no – even ifyou want to read data into alternate buffers, so you can process one bufferwhile reading the next, you can still follow the pattern of only having oneoutstanding call to ReadL() but supplying a different descriptor eachtime.Having said all this, there is a requirement for this code to run in a‘timely manner’ – if you delay calling ReadL() for too long, then theunderlying system runs out of space to write its data.

On some systems, thisresults in a KErrOverflow error on the MaiscRecordComplete()callback:void CIOStreamAudio::MaiscRecordComplete(TInt aError){ASSERT(iState == EStateReading && aError != KErrNone);Complete(aError);}This has an implicit Stop() action; that is, if an error occurs, it is asif Stop() has been called on the audio input stream and you don’t haveto call Stop() yourself. As shown here, all you can do is to notify theclient application.

As well as overflow, you will see other errors such asinternal errors and also ‘throw-offs’ where the underlying layer decidesto stop you to allow something else to run (see Section 5.8).114MULTIMEDIA FRAMEWORK: AUDIO5.2.3 Stream Calls for PlayingIn this example, the trigger to stop recording and to play the descriptoris the StopAndPlay() call from the parent application. This is fairlysimple:void CIOStreamAudio::StopAndPlay(){if (iState == EStateReading){// no effect unless we are actually recordingiInputStream->Stop();iObserver->RecordingStopped();iOutputStream->Open(NULL); // needs to agree with what we gave// to the input streamiState = EStateOpeningOutput;}}It stops the recording, notifies the client – assumed to be useful herebut that depends on your client – and then proceeds to play.There is a potential defect here when recording: calling CMdaAudioInputStream::Stop() is simple to use but any outstanding datathat has been captured from the microphone and not passed to theclient is lost.

This is usually not important – it will be a fraction of asecond. If it is important, then versions of CMdaAudioInputStreamfrom Symbian OS v9.3 have an additional call, RequestStop(),which immediately stops recording at the microphone but still passesdata through. If you use this call, your application should keep goinguntil MaiscRecordComplete() is received, at which point theaudio input stream object is stopped.

Характеристики

Тип файла
PDF-файл
Размер
1,13 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6372
Авторов
на СтудИзбе
309
Средний доход
с одного платного файла
Обучение Подробнее