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

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

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

Then you probably want to query the capabilities ofeach using the CMMTunerUtility::GetCapabilities() methodand choose which one to use based on the results returned. The simpleexample below illustrates this approach; it picks the first available FMtuner with RDS support:TInt availableTuners = CMMTunerUtility::TunersAvailable();// This will hold the index of the desired tunerTInt desiredTuner = KErrNotFound;// This is populated by GetCapabilities()TTunerCapabilities tunerCaps;for( TInt i = 0; i < availableTuners; ++i ){// skip the tuner if this fails for some reasonif (CMMTunerUtility::GetCapabilities(i, tunerCaps) != KErrNone){continue;}if ((tunerCaps.iTunerBands & ETunerBandFm) &&(tunerCaps.iAdditionalFunctions & ETunerFunctionRds) ){// found a tuner with FM and RDSdesiredTuner = i;break;}}// End of for loopif (desiredTuner == KErrNotFound ){ // No suitable tuners on this deviceUser::Leave( KErrNotFound );}200THE TUNER APITo create a CMMTunerUtility, you need to supply an observerclass that implements the MMMTunerObserver interface.

You shouldimplement the observer code, which requires two methods to be defined:one to deal with the completion of asynchronous tuning operations andanother to handle tuner control events and errors.iMyTunerUtility = CMMTunerUtility::NewL(*iMyTunerObserver, desiredTuner);Once the call to NewL() returns, the tuner utility has been createdand initialized and is ready to be used.7.2.2 Control and PrioritiesIt is possible for more than one instance of the Tuner API to be present atthe same time. For instance there could be multiple applications runningsimultaneously, each of which use the API.

This could potentially leadto problems such as two separate applications trying to tune to differentfrequencies at the same time. To prevent this, the API has been designedso that only one instance can be in control of the tuning functions at anygiven time. A tuner instance automatically attempts to gain control thefirst time one of the tuning functions is used (e.g. Tune()). It may alsorequest control explicitly by calling RequestTunerControl().When an instance of CMMTunerUtility attempts to use the tuningfunctions while another instance has control, it is notified that the attemptfailed via a callback to the MMMTunerObserver::MToTunerEvent()with a KErrPermissionDenied error. Use of the tuning functions willnot succeed until Close() is called on the other tuner instance or itreleases its control by calling ReleaseTunerControl().Each tuner instance is assigned an access priority when it is initialized(there is an optional access priority parameter for NewL() that can beused to request a higher or lower access priority than the default).3 Tunerinstances with higher priorities can pre-empt those with a lower priorityand take over control.

In this case, the instance with the lower priorityis notified that it has been displaced via the tuner observer method. Forthis reason, applications that use the tuner should be written to handlepre-emption by a higher-priority client at any time. Depending on the usecase, it may be desirable to notify the user that this has occurred, to waitand try to regain control of the tuner automatically, or to do nothing untilthe user interacts with the application again.3 Priorities higher than ETunerAccessPriorityNormal require the MultimediaDDplatform security capability, which is restricted and requires that your application is SymbianSigned using the Certified Signed route.

These priorities are intended for things such as abuilt-in radio-alarm function on a phone, which must be able to interrupt any other tunerapplications in order to sound the alarm.BASIC USE CASES201If your tuner instance fails to get control or is pre-empted by another,you can use NotifyTunerControl() to request a notification callbackvia the tuner observer when control becomes available again.7.2.3 CleanupWhen your application has finished using the tuner API, it must deleteits instance of CMMTunerUtility. This does all the necessary cleanupbehind the scenes and, if no other applications are using the tuner, powersdown the tuner hardware. However, if you use any of the other utilityclasses (e.g.

CMMTunerScannerUtility) then these must be deletedbefore deleting the main CMMTunerUtility.There is also a Close() method available on CMMTunerUtilitywhich does the same de-initialization except that your instance of CMMTunerUtility is not deleted. This may be useful if your tuner utility isa member variable which is deleted by the owning class’s destructor butis known not to be needed earlier.

It is not necessary to delete associatedutility classes before calling Close(); any ongoing activity is stoppedautomatically.7.3 Basic Use Cases7.3.1 TuningTuning to a particular frequency is done via the Tune() method, whichis an asynchronous command. Success or failure of a tuning operation isreported via the MToTuneComplete() method on the tuner observer.As mentioned in Section 7.2.2, calling Tune() automatically requestscontrol of the tuner, if necessary. The method takes two parameters:• the frequency (given in Hertz, so 95.8 MHz would be 95,800,000 Hzfor example)• the frequency band (FM, AM, LW, etc.).4You can also query which frequency the tuner is currently set to at anytime by using the GetFrequency() method.7.3.2 Playing the RadioOnce you have tuned to a frequency, you probably want to play thesound.

This is handled by the CMMTunerAudioPlayerUtility class.4 There is a version of Tune() that takes digital channel numbers instead of frequencies.It was put in by Symbian for future-proofing and is intended for systems such as DAB.However, at the time of going to press, there are currently no UIQ3 handsets that supportthis (see Section 7.4.1).202THE TUNER APIThere can only ever be one instance of this class per instance of theCMMTunerUtility and it is retrieved using the GetTunerAudioPlayerUtilityL() method. This method expects an observer thatimplements the MMMTunerAudioPlayerObserver interface, whichhandles callbacks from the tuner audio player (more on these ina moment).Before playback can commence, you must initialize the tuner audioplayer by calling its InitializeL() method.

Success or failure ofthe initialization is signaled via the observer’s MTapoInitializeComplete() method.There are two optional parameters that set the sound device priorityand priority preference. These are distinct from the tuner utility’s prioritysetting. They behave just like the sound device priority settings for theMMF’s audio player utilities, i.e. they are device-specific and may beignored unless your application has the MultimediaDD capability.

Inmost cases, omitting these values and using the defaults should be justfine! However, if you wish to learn more about sound device prioritiesthen please refer to Chapter 5.Once your CMMTunerAudioPlayerUtility has been initialized,you can start playback by calling Play(). To temporarily stop playback,use the Mute() method because the Stop() method releases the audiodevice and playback cannot be restarted afterwards.

Only use Stop()when you don’t need the tuner audio player utility any more, such aswhen shutting down your application.The following example demonstrates these steps:// get tuner audio player utilityiMyTunerAudioPlayer = iMyTunerUtility->GetTunerAudioPlayerUtilityL(*iMyTunerAudioPlayerObserver);// initialize itiMyTunerAudioPlayer->InitializeL();// now we can start playingiMyTunerAudioPlayer->Play();// ...// when we are done...// stopiMyTunerAudioPlayer->Stop();// clean updelete iMyTunerAudioPlayer;iMyTunerAudioPlayer = NULL;7.3.3 Recording from the RadioThe CMMTunerAudioRecorderUtility allows you to record audiofrom the radio to a file or descriptor. It behaves in much the same wayas the tuner audio player utility.

One of the differences is that InitializeL() has additional parameters to specify the recording destinationBASIC USE CASES203and format. Please check the Symbian Developer Library documentationreference guide for CMMTunerUtility::GetTunerAudioRecorderUtility() and class CMMTunerAudioRecorderUtility formore information.7.3.4 Scanning for FrequenciesA useful feature is to scan frequencies automatically for strong signals.This can be achieved by using the tuner utility’s StationSeek()method. It takes a start frequency, a tuner band, and a search direction(up or down); it searches until it finds the next strong signal and tunesinto it. At this point, you receive a callback on the tuner observer’sMToTunerEvent() method with an event type of ETunerEvent.

Ifyou want to know what frequency was found, you can retrieve it via thetuner utility’s GetFrequency() method.If you are listening to the radio while it is seeking stations, youmay hear noise in between the radio stations. To avoid this you canenable ‘squelching’ (muting in frequencies without reception) using theSetSquelch() method.7.3.5 Automated Scanning using the Scanner UtilityA common use case is to find all available radio stations in the area. Tosimplify this you can use the scanner utility class, CMMTunerScannerUtility, which is a convenience wrapper that scans through all available frequencies pausing at each discovered station for a specified amountof time.To get the scanner utility you simply use the tuner utility’s GetTunerScannerUtilityL() method.

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

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

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

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