quick_recipes (779892), страница 45

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

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

Note that calling this method will cause the callback method,MaoscBufferCopied(), to be called with KErrAbort error code,and MaoscPlayComplete() with KErrCancel. If you are handlingthe error code in those methods, you have to exclude this situation.Otherwise, you will get an error message when stopping the audiostreaming.What may go wrong when you do this: After you have finishedplaying the stream, you have to stop the stream or destroy the instanceof CMdaAudioOutputStream. If you don’t do this, the audio deviceis actually still on.

This will drain the battery.MULTIMEDIA2534.7.3 Advanced Recipes4.7.3.1Record AudioAmount of time required: 20 minutesLocation of example code: \Multimedia\AudioRecordingRequired libraries: mediaclientaudio.libRequired header file(s): MdaAudioSampleEditor.hRequired platform security capability(s): UserEnvironmentProblem: You want to record audio from the device microphone ortelephone downlink.Solution: The class to record audio is CMdaAudioRecorderUtility.Here are the steps to record audio:• Create a new instance of CMdaAudioRecorderUtility, whichimplements MMdaObjectStateChangeObserver.• Open the fileOpenFileL().bycallingCMdaAudioRecorderUtility::• Wait until the observer method, MMdaObjectStateChangeObserver::MoscoStateChangeEvent(), is called.• Start recordingRecordL().bycallingCMdaAudioRecorderUtility::• Stop recording by calling CMdaAudioRecorderUtility::Stop().The recording method, CMdaAudioRecorderUtility::RecordL(), requires the UserEnvironment capability.Like other audio APIs, the supported formats and codecs vary betweendevices.In our recipe, the CSimpleAudioRecorder class implements MMdaObjectStateChangeObserver.Discussion: CMdaAudioRecorderUtility::OpenFileL() opensthe file where the audio sample data will be recorded.

It selects theMMF controller automatically based on the file extension. For example,when you specify .amr as the file extension, the controller plug-in forAMR will be loaded.When the audio file has been opened, the observer method, MoscoStateChangeEvent(), is called. This callback method has fourparameters:void CSimpleAudioRecorder::MoscoStateChangeEvent(CBase* aObject,TInt aPreviousState, TInt aCurrentState, TInt aErrorCode)254SYMBIAN C++ RECIPESThe aObject parameter is the object of the recorder utility. It is usefulwhen you have more than one recorder utility object.The aPreviousState and aCurrentState parameters are theprevious state and the current state of the audio sample, respectively.There are several values defined in CMdaAudioClipUtility that canbe assigned to them:• ENotReady. The audio clip recorder has been constructed but no filehas been opened.• EOpen.

The file is opened but no recording or playing is in progress.• ERecording. New audio sample data is being recorded.• EPlaying. Audio sample is being played.aErrorCode is the system-wide error code, as defined in \epoc32\include\e32err.h.What may go wrong when you do this: The RecordL() methodappends the new recorded audio to an existing file. There is a method,CMdaAudioRecoderUtility::CropL(), that is supposed to discard any existing data before recording. Unfortunately, it does notwork with AMR on some S60 devices.

In order to support compatibility with as many devices as possible, it is recommended notto use CropL(). If you want to delete existing data, you can useBaflUtils::DeleteFile() before recording audio.What may go wrong when you do this: If you don’t specify theUserEnvironment capability in the MMP file, you will get theKErrAccessDenied (-21) error code in the MoscoStateChangeEvent() observer.If your recorded clip is distorted, try a lower gain value by callingCMdaAudioRecoderUtility::SetGain().There are several recording settings that can be adjusted, such ascodec, sampling rate, bit rate and number of channels.

The recipe usesthe default settings.Tip: It is possible to set the maximum length of the file that is beingrecorded by calling CMdaAudioRecorderUtility::SetMaxWriteLength(). It requires one parameter, which is the maximum file size in bytes (not kilobytes, as indicated by some SDKdocumentation).MULTIMEDIA255Tip: The CMdaAudioRecorderUtility class can also be usedto play an audio file, using the PlayL() method. Take a look atCSimpleAudioRecorder::PlayRecordedL() in the recipe tosee how to use it.4.7.3.2Record a Phone CallThe previous recipe, which showed audio recording, can be used torecord a phone call.

Once you have called CMdaAudioRecorderUtility::RecordL(), audio from the local speaker and telephonydownlink will be recorded. Unfortunately, it is not possible to recordsolely from one source (local speaker or telephony downlink only)because the API, CMdaAudioRecorderUtility::SetAudioDeviceMode(), has been deprecated.It is also possible to create an answering machine that automaticallyrecords a caller’s message from the telephony downlink. To create suchan application, you need to use CMdaAudioRecorderUtility andCTelephony. Please see the recipes in Section 4.8 for a discussionabout CTelephony. The idea is to start recording once an incoming callis detectedThe audio recording recipe would have to be modified to monitortelephony events to decide when to start and stop recording.Tip: Recording a phone conversation is illegal in some countries.Some of them require the person to be notified that the conversation isrecorded.

That is why some Nokia phones output a beep sound everyfew seconds when recording is happening. This is to notify the otherparty on the line that the conversation is being recorded.4.7.3.3Display a Camera ViewfinderAmount of time required: 30 minutesLocation of example code: \Multimedia\CameraImageRequired libraries: ecam.libRequired header file(s): ecam.hRequired platform security capability(s): UserEnvironmentProblem: You want to display the viewfinder of a camera on yourapplication.Solution: Symbian OS provides the Onboard Camera API, which is anopen and extensible generic API for controlling digital camera devices.

Itcan be used to capture still images and record videos.256SYMBIAN C++ RECIPESThe CCamera class provides the base class for camera devices. Itprovides virtual methods for controlling a camera, such as acquiringimages and videos. Phone manufacturers derive CCamera and providetheir implementations.There are two observer classes for CCamera: MCameraObserver andMCameraObserver2. MCameraObserver2 is the recommended API.Unfortunately, at the time of writing this book, S60 devices do not supportMCameraObserver2 yet.

In order to maintain compatibility with S60devices, this book uses MCameraObserver in the examples.In our recipe, the viewfinder is handled by the CCameraEngine class.Discussion: A number of Symbian smartphones have two camera devices,which is why the NewL() factory method of the CCamera class allowsyou to choose a camera index between 0 and (CCamera::CamerasAvailable() - 1).

The camera at index 0 is usually the one with thehigher resolution, pointing away from the handset user. A bad cameraindex will cause a panic.Getting camera informationThe TCameraInfo class specifies camera information, such as supportedimage format, flash support, zoom support and many others. You can getcamera information by calling CCamera::CameraInfo().In the recipe, we use TCameraInfo::iOptionsSupported, whichhas the type of TOptions. It is a bit flag that stores the camera’s supportedoptions. Here is the list of possible values of the bit flag:• EViewFinderDirectSupported• EViewFinderBitmapsSupported• EImageCaptureSupported• EVideoCaptureSupported• EViewFinderMirrorSupported• EContrastSupported• EBrightnessSupported• EViewFinderClippingSupported• EImageClippingSupported• EVideoClippingSupported.There are several values that are related to the viewfinder, but for thisexample we will be using the first two values only.

There are basicallytwo viewfinder types:MULTIMEDIA257• Direct viewfinder (EViewFinderDirectSupported). The viewfinder can be drawn using direct screen access. It is easier to use andhas a better performance. Unfortunately, not all devices support thismode; for example, at the time of writing this book, S60 devices donot support direct viewfinder mode.• Bitmap viewfinder (EViewFinderBitmapsSupported). The viewfinder has to be drawn manually via a bitmap to a device context.Initializing cameraThere are two steps involved in initializing the camera:• Reserve the camera for exclusive use by calling CCamera::Reserve().

This is an asynchronous method. When complete, it willcall MCameraObserver::ReserveComplete().The camera reservation is based on priority. That means, if there aretwo applications attempting to reserve a camera, the application withthe higher priority will preempt the lower one. As with audio, youneed MultimediaDD capability to change the priority.• Switch on the camera power by calling CCamera::PowerOn().This has to be called after Reserve() has been called.

It is alsoan asynchronous method. When complete, it will call MCameraObserver::PowerOnComplete().After you have finished using the camera, you have to turn it off bycalling CCamera::PowerOff(). Otherwise, your application will drainthe battery very fast.What may go wrong when you do this: The camera consumes a lotof battery power.

If you don’t use the camera, you have to turn it off.You can react to your application being sent to the background byoverriding CAppUi::HandleForegroundEventL().Displaying the viewfinderThere are two methods to display the viewfinder. These are CCamera::StartViewFinderDirectL() and CCamera::StartViewFinderBitmapsL().

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

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

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

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