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

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

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

It has been testedon the Sony Ericsson P1. The tuner implementation is identical on otherSony Ericsson smartphones based on Symbian OS v9.1.8Best PracticeThis chapter is a collection of guidelines that apply to using the various multimedia APIs. Some may be more obvious than others, but allshould save you some development time and frustration. All the usualSymbian C++ good practice applies too,1 but we’ll skip that for thisdiscussion.8.1 Always Use an Active SchedulerThis can’t be stated enough: the multimedia subsystem cannot workwithout proper use of an active scheduler and associated active objects.Some APIs (for example, within ICL) explicitly use TRequestStatusto show asynchronous behavior and expect the client to drive them viaan active object. With others, the behavior is callback-based and itsasynchronous nature is hidden.

Virtually all the APIs make extensive useof CActive-based active objects behind the scenes and need an activescheduler to operate correctly.When making function calls from your main application, this shouldseem self-evident, because the same rules apply to the application framework. On Symbian OS, all standard applications run within an activescheduler, with calls made from the RunL() calls of individual activeobjects.

You have to make an asynchronous call from one RunL()instance and exit without waiting for the response. For example, whenhandling menu events, you might write the following code to open a clipin a descriptor, pending play:iPlayer->OpenDesL(*iMyBuffer);1Advice for C++ developers new to Symbian OS can be found in a range of SymbianPress books and booklets, available from developer.symbian.com/books , and in articlespublished online at developer.symbian.com.210BEST PRACTICEYou can fire off several such calls, but should then return through theAppUi::HandleCommandL() call or equivalent.

At some later stage,the callbacks are made by the associated API implementation. At the rootof these callbacks, there is always a RunL() call; if you have access tothe Symbian OS source code then you can see this in the stack tracewhen you’re debugging on the Windows emulator.If you are running within the main application thread, this allcomes for free – the standard application environment is itself basedon active objects and needs an active scheduler.

If you create yourown threads, you need to create and install an active scheduler to getthis to work. If you forget, the result is unpredictable – depending onthe API – but, in general, not much will happen. The active objects areused not just for callback support but also for internal asynchronousprocessing.Sometimes, you find yourself calling an asynchronous call from whatwas previously a synchronous function, for example when you aremodifying existing applications to use the multimedia calls. It is preferableto redesign your main program: for instance to re-classify the callingfunction as asynchronous, so the underlying action is not considered‘finished’ on return and to allow for actions in the background.

Sometimesthis is not possible or it looks undesirable. One option in this scenariois to use the CActiveSchedulerWait class, for which documentationis available in the Symbian Developer Library (in the Base section of theSymbian OS Reference).Our experience is that it is less of a problem to use asynchronous stylesof programming rather than forming synchronous calls from asynchronousones. However, this is sometimes all you can do – sometimes you haveto fit into an existing API structure that is synchronous.

This is oftenthe case if you are using existing code modules, perhaps ported fromanother operating system. If you do use CActiveSchedulerWait, thentake extra care not to block program input while a relatively long actionis occurring. Remember, the RunL() method in which you start theCActiveSchedulerWait is blocked until it returns.8.2 Use APPARC to Recognize Audio and VideoAs we noted in Chapters 4 and 5, the multimedia framework providesseparate APIs for audio and video clip usage.

Depending on the applications you are developing, you may want to handle both – i.e. given a file,you may want to use the video APIs for video files and the audio APIs foraudio files. The question is how do you do this?One approach would be to guess: to try to open a file as video andthen open it as audio if this fails. This should be avoided for severalreasons:USE APPARC TO RECOGNIZE AUDIO AND VIDEO211• MMF might manage to partially open the clip – only for it to failtowards the end of the sequence. It is comparatively expensive toopen a multimedia clip – involving loading several plug-ins – so thismay slow down your application.• MMF might actually succeed in opening the clip in the wrong mode!You may open an audio file using the video API, with an associatedblank screen – it depends on how the plug-ins behave.

More likely, avideo file opened as audio may legitimately support playing the audiochannel.The recommended approach is to use the application architectureserver2 to find the MIME type:// Link against apgrfx.lib#include <APGCLI.H>RApaLsSession lsSession; // assume already connectedRFile fileToTest; // assume already openedTDataRecognitionResult result;TInt error = lsSession.RecognizeData(fileToTest, result);TPtrC8 mimeType = result.iDataType.Des8();Once we have this information, we can decide whether it is an audioor video clip by checking the MIME type:const TInt KLength = 6; // either "audio/" or "video/"_LIT(KAudio, "audio/");_LIT(KVideo, "video/");if (mimeType.Left(KLength).Compare(KAudio)==0){// Treat as audio}else if (mimeType.Left(KLength).Compare(KVideo)==0){// Treat as video}else{// special case}A WAV file would show as ‘audio/wav’ and a 3GPP video file as‘video/3gpp’.

For this exercise, we’re not so much interested in the wholestring but in the first part (officially, the ‘type’). In most cases, a clipwhose MIME type begins with ‘audio/’ can be opened using the standardaudio client APIs, e.g. CMdaAudioPlayerUtility, and one beginningwith ‘video/’ can be opened with CVideoPlayerUtility – the same2 Information about APPARC can be found in the Symbian Developer Library documentation in your SDK or online at developer.symbian.com.212BEST PRACTICEtechnique shows up other classes of file and can be easily extended.If there are specific formats that the application wishes to handle in aparticular way, then the whole MIME type can be tested.A variation on this is where the application already has a MIME typefor the clip but may still prefer to use APPARC.

For example, for browsertype applications, the MIME type is often supplied by the server as partof the download protocol. Using this has some advantages: you get toknow the MIME type before downloading the file and it ought to befaster. However, there are a couple of disadvantages that might not beimmediately apparent:• For many types of file, there are actually several legal MIME types.For example, WAV files can be ‘audio/x-wav’ or ‘audio/wav’ – ‘audio/x-wav’ is perhaps best thought of as deprecated although is still legal.The Symbian recognizer should consistently indicate ‘audio/wav’ asthe MIME type.

Another system may vary in this regard. If you rely onthe supplied MIME type, take extra care.• For some file types, there are very similar ‘audio’ and ‘video’ versions.For example, an MP4 file may contain only audio data or may alsocontain video. As a first degree of approximation, the recognitionsystem should look through the file for references to video – if found,it is treated as a video file; if not, as an audio file. Other systems maynot do this.In general, it is probably safer to ignore the supplied MIME type anduse APPARC, as described.

However, if you have yet to download thefiles then go for the supplied version – just take care!8.3 Don’t Use the Video Player to Open Audio FilesIn some formats, it is possible to open an audio file using CVideoPlayerUtility. However, this should not be relied upon; neither isit efficient. It may work on some variations of a device but not others,depending on what plug-ins are installed. It is better to use the videoAPIs to open video clips and the audio APIs to open audio clips.

SeeChapters 4 and 5, respectively.8.4 Know that MMF and ICL Cannot Detect Some FormatsThis can be thought of as the inverse of the guideline in Section 8.2!Most of the time, if you give MMF or ICL a file, it can open that fileDON’T USE CMdaAudioOutputStream FOR NETWORK STREAMING213and subsequently play or decode it, without you having to supply anymore information.

The mechanism behind this relies chiefly on therebeing a number or string at the beginning of a file that can reliablyidentify the format. This is true for most multimedia files, but not all andsome relatively common file formats don’t provide it, including MP3 andWBMP (Wireless Bitmap) files. In such scenarios, it is normal to use thefilename extension.So far so good, but what about when there is no suffix – such as whenreading data from a descriptor? This can present a problem, and there area number of different approaches:• Don’t use descriptors when you don’t know the file format – if youknow the suffix, when downloading a file for example, use a temporaryfile.• If you know the MIME type (sometimes this is supplied by thecommunications protocol), then use it.• If anonymous opening does not work, then use the APPARC serverto recognize and supply the MIME type.

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

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

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

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