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

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

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

Where an API method is called before an operation it requires hascompleted, an error will be returned directly from the API method call orvia your callback observer.In the following sections, we go into more detail about each of thespecific API classes and the methods that they provide. It is assumedthat the information in this book will be used in conjunction with theSymbian Developer Library documentation, which can be found in everySDK or online at developer.symbian.com. This book shows how the APImethods can be used, but the documentation should be used for detaileddescriptions of each of the individual parameters and the return valuesfor the API methods.Where the following sections show a particular method, then thatmethod is normally available through both the CVideoPlayerUtility class and the CVideoPlayerUtility2 class.

There are a fewexceptions to this, such as where the CVideoPlayerUtility2 classhas extra functions or where different versions of the same function existbetween the two classes, and these are indicated in the relevant sections.4.4 Identifying Video ControllersSome of the client API methods allow you to specify the UID of the videocontroller that you want to use for the playback or recording operation.11 Note that this is essential for recording but not good practice for playback – seeSection 8.8 for details.62MULTIMEDIA FRAMEWORK: VIDEOIf you want to find a list of the controllers that exist on the phone then youcan use some code similar to this example. It uses the MMF frameworkto access the list of controllers, and then retrieves the play formats thatare supported:CMMFControllerPluginSelectionParameters* cSelect =CMMFControllerPluginSelectionParameters::NewLC();CMMFFormatSelectionParameters* fSelect =CMMFFormatSelectionParameters::NewLC();RArray<TUid> mediaIds;mediaIds.Append(KUidMediaTypeVideo);cSelect->SetMediaIdsL(mediaIds,CMMFPluginSelectionParameters::EAllowOtherMediaIds);// Indicate that we want to retrieve record formatscSelect->SetRequiredRecordFormatSupportL(*fSelect);// Populate an array of controllers that can recordRMMFControllerImplInfoArray controllers;CleanupResetAndDestroyPushL(controllers);cSelect->ListImplementationsL(controllers);TInt numControllers = controllers.Count();for (TInt i = 0; i < numControllers; ++i){RMMFFormatImplInfoArray& playFormats = controllers[i]->PlayFormats();if (playFormats.Count() > 0){// If you just want the first controller that can play then you can// get its UID and the UID of the format now using code like this...// iControllerUid = controllers[i]->Uid();// iFormatUid = playFormats[0]->Uid();// break;//// Alternatively you may want to request the supported container file// MIME types, if you want a particular controller, like this...// const CDesC8Array* fileExtensions = &playFormats[0]->//SupportedMimeTypes();}}CleanupStack::PopAndDestroy(3, cSelect);This example is incomplete; the commented out code shows examplesof what you can do with it.

For instance, it shows how you would get theUID for a particular controller.4.5 Controlling Video PlaybackFigures 4.2 and 4.3 show the user interactions for the basic play andpause/stop sequences for video playback of a file. They show theAPI method calls from the user and the callbacks from the CVideoPlayerUtility class. In the following sections, we look at these APImethod calls in more detail.CONTROLLING VIDEO PLAYBACK63UserCVideoPlayerUtilityNewL()OpenFileL()MvpuoOpenComplete(KErrNone)Prepare()MvpuoPrepareComplete(KErrNone)Play()MvpuoPlayComplete(KErrNone)Close()~CVideoPlayerUtility()Figure 4.2 Play sequence4.5.1 Creating the Playback ClassesBoth CVideoPlayerUtility and CVideoPlayerUtility2 are instantiated by calling their static NewL() methods (see Figure 4.2):static CVideoPlayerUtility* NewL(MVideoPlayerUtilityObserver& aObserver,TInt aPriority,TMdaPriorityPreference aPref,RWsSession& aWs,CWsScreenDevice& aScreenDevice,RWindowBase& aWindow,const TRect& aScreenRect,const TRect& aClipRect);64MULTIMEDIA FRAMEWORK: VIDEOstatic CVideoPlayerUtility2* NewL(MVideoPlayerUtilityObserver& aObserver,TInt aPriority,TMdaPriorityPreference aPref);The NewL() factory methods of CVideoPlayerUtility andCVideoPlayerUtility2 share some common parameters:• The observer parameter, aObserver, is a class that provides the setof callback functions for asynchronous API calls.• The parameters aPriority and aPref are used to decide whichclient should take priority when two separate clients require accessto the same sound device, for instance where a video is beingplayed on the loudspeaker and a telephone call is received whichrequires a ringtone to be played.

These parameters are explained inSection 4.9.1.The CVideoPlayerUtility::NewL() factory method also requiresa number of parameters that provide information about the display to beused. These are explained in Section 4.6.1.The CVideoPlayerUtility2::NewL() routine does not requireany display-related parameters to be passed to it. This is because thedisplay information is set by a separate call to the AddDisplayWindowL() method as described in Section 4.6.1.The observer parameter to the NewL() methods is a reference to aclass that is derived from the MVideoPlayerUtilityObserver class.The MVideoPlayerUtilityObserver class defines a set of methodsthat the derived class must implement.

These methods are then calledwhen certain asynchronous operations are completed.class CMyVideoPLayerObserver : public CBase,public MVideoPlayerUtilityObserver{public:void MvpuoOpenComplete(Tint aError);void MvpuoPrepareComplete(Tint aError);void MvpuoFrameReady(CFbsBitmap& aFrame, Tint aError);void MvpuoPlayComplete(Tint aError);void MvpuoEvent(const TMMFEvent& aEvent);};MVideoPlayerUtilityObserver provides methods that are calledon the completion of an open operation, a prepare operation, a requestto fetch an individual frame and the play operation. Each of the callbacksincludes an aError parameter which can be checked to see if the operation completed correctly or not. In addition, a general event reportingCONTROLLING VIDEO PLAYBACK65callback, MvpuoEvent, is defined which supports things such as errorhandling.

The event consists of a UID which defines the event typeand an associated error code. Normal system-wide errors have theUID KMMFErrorCategoryControllerGeneralError; in addition,video controllers may define their own event types with their own specificUIDs. Note however that the authors of a video controller on a phonemay choose not to make public the information about the events thattheir controller can generate.4.5.2 Opening a VideoThere are three methods that are available for opening a file containinga video:void OpenFileL(const TDesC& aFileName, TUid aControllerUid = KNullUid);void OpenFileL(const RFile& aFileName, TUid aControllerUid = KNullUid);void OpenFileL(const TMMSource& aSource, TUid aControllerUid = KNullUid);You can specify a file name, a handle to an already opened file, or aTMMSource, which allows access to a DRM-protected source.

There isone method that allows you to open a video contained in a descriptorbuffer:void OpenDesL(const TDesC8& aDescriptor, TUid aControllerUid = KNullUid);There is one method that allows you to open a video for streaming:void OpenUrlL(const TDesC& aUrl, TInt aIapId = KUseDefaultIap,const TDesC8& aMimeType = KNullDesC8,TUid aControllerUid = KNullUid);You are required to specify the URL that you want to stream from, anaccess point that is used to make the connection to that URL, and theMIME type of the video. Current Symbian smartphones generally requirethat the URL you supply is an RTSP URL.All the open methods allow you to specify the UID of a specific videocontroller that you want to use. Normally the video controller is chosenbased on the type and contents of the specified file but, by specifyingthe UID, you can override this decision and use a controller of yourchoice.

This mechanism can also be used where the file does not have arecognizable extension but you know what the file format is.Opening a video is an asynchronous event, so you must wait forthe MvpuoOpenComplete() method of your observer to be completedbefore proceeding. If the open operation fails then the initial API call66MULTIMEDIA FRAMEWORK: VIDEOcan leave with an error or an error code can be passed to the observermethod. You need to handle both these scenarios when using these APIs.4.5.3 Preparing a VideoOnce the video has been opened successfully, you need to prepare thevideo to be played:void Prepare();This tells the video controller to prime itself, ready to start playing.The controller allocates any buffers and resources required for playbackat this point.Preparing a video is an asynchronous event, so you must wait for theMvpuoPrepareComplete() method of your observer to be completedbefore proceeding.4.5.4 Playing a VideoOnce the prepare operation has completed, you can start playing thevideo (see Figure 4.3):CVideoPlayerUtilityUserPlay()Pause()Play()Stop()Figure 4.3 Pause and stop sequenceCONTROLLING VIDEO PLAYBACK67void Play();void Play(const TTimeIntervalMicroSeconds& aStartPoint,const TTimeIntervalMicroSeconds& aEndPoint);Calling Play() with no parameters causes playback to start from thebeginning of the video and finish at the end of the video.

You can alsospecify start and end time parameters, which cause playback to start andend at the designated points in the video.Video playback is an asynchronous event. You know video playbackhas completed when the MvpuoPlayComplete() method of yourobserver is called. If playback finishes early due to an error then the errorcode is passed to the observer method.4.5.5 Pausing a VideoYou can pause the current video playback operation:void PauseL();This is a synchronous operation.

It leaves with an error code if thepause operation fails. Call Play() to restart the playback from the pausedposition.4.5.6 Stopping a VideoYou can stop the current video playback operation:TInt Stop();This is a synchronous operation and returns an error code if a problemoccurs while stopping the video.The Symbian Developer Library documentation, found in each SDK,states that if you stop a video while it is playing, the MvpuoPlayComplete() method of your observer will not be called, however asthis is controlled by the video controller it is safer to assume that you mayreceive this call.68MULTIMEDIA FRAMEWORK: VIDEO4.5.7 Closing a VideoYou can close the currently opened video:void Close();4.5.8 Setting the Video PositionIt is possible to change the position that the video is playing from usingthe SetPositionL() method:void SetPositionL(const TTimeIntervalMicroSeconds& aPosition);If you call this method before the video has started playing, it changesthe position that playback will start from.

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

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

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

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