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

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

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

You can findthis documentation in your development SDK, or read it online on theSymbian Developer Network:• developer.symbian.com/main/oslibrary/osdocs.Both S60 and UIQ SDKs can be upgraded to support OpenGL ES 1.1:• www.developer.sonyericsson.com/getDocument.do?docId=84947.• www.forum.nokia.com/info/sw.nokia.com/id/36331d44-414a4b82-8b20-85f1183e7029/OpenGL ES 1 1 Plug in.html.The Symbian Press book Games on Symbian OS discusses OpenGLES and other Khronos standards. It also includes further discussion of thefactors to consider when creating smartphone games:• developer.symbian.com/gamesbook.4.7 MultimediaThese recipes discuss aspects of working with multimedia files, such asplaying and recording audio or video.Symbian OS provides a framework called MMF (Multimedia Framework) which supports the following:• audio playing, recording and conversion• audio streaming• tone playing• video playing and recording.The MMF is an extensible framework that allows phone manufacturersand third parties to add plug-ins to provide support for audio and videoformats.

For the application developer, it provides APIs that abstract theunderlying hardware, thereby simplifying the code needed to record andplay the content. The streaming APIs provided by the framework, whichbypass large parts of the MMF, offer a lower-level interface that allowsstreaming of audio data to and from the audio hardware.MULTIMEDIA237MMF Client APIAudio InterfaceVideo InterfaceRecord, play & convertRecord & playMMF Controller FrameworkTone PlayerInterfaceAudio StreamingInterfaceTones and DTMFStreaming audio in & outThread BoundaryAudio controllerplug-insVideo controllerplug-insDevSoundCodecplug-insFigure 4.7.1 Architecture of MMFFigure 4.7.1 shows the architecture of MMF.The default Symbian OS MMF implementation supports basic audioformats.

For example, for audio playback, it supports AU and WAVfiles and provides codecs for pulse code modulation (PCM) format.Furthermore, in addition to basic formats, most Symbian OS phonesprovide support for playback of other popular formats. For audio, thisincludes MP3, advanced audio coding (AAC), and adaptive multi-rate(AMR). Phone manufacturers supply additional controller plug-ins onlyto selected devices because of dependencies on specific acceleratedhardware components, licensing issues, DRM requirements, or otherbusiness factors.In this set of recipes, we will also discuss the Onboard Camera API,which is a generic and extensible API for controlling an onboard digitalcamera on devices.

It supports either still images or videos. Please referto the recipes in Section 4.5 for a discussion about image processing andgeneral 2D graphics.As a client of the Symbian OS multimedia APIs, you’ll find a lot ofthe code you write will be implementation of the observer interfacesthat are passed to the API and called by the MMF to signal an eventor change of state. There is quite a lot to discuss in these recipes and,for clarity, we are going to quote the minimum of source code possible.You can find the full set of example code available for download atdeveloper.symbian.com/symbian press cookbook.238SYMBIAN C++ RECIPESFurther information about MMF and working with multimedia contenton Symbian OS is available from the Symbian Developer Library documentation in your SDK, or online on the Symbian Developer Network (atdeveloper.symbian.com/main/oslibrary/osdocs).4.7.1 Easy Recipes4.7.1.1Play an Audio ClipAmount of time required: 15 minutesLocation of example code: \Multimedia\AudioPlayingRequired libraries: mediaclientaudio.libRequired header file(s): MdaAudioSamplePlayer.hRequired platform security capability(s): NoneProblem: You want to play an audio clip from a file, such as a WAV,MP3 or AAC file.Solution: The client API to play an audio clip from a file is the CMdaAudioPlayerUtility class.

CMdaAudioPlayerUtility requiresan observer class, which implements MMdaAudioPlayerCallback.The observer will be notified when the audio clip has been initialized orplayed completely.The following steps explain how to play an audio clip using CMdaAudioPlayerUtility:1.Create an observer class, which implements MMdaAudioPlayerCallback.2.Create an instance of CMdaAudioPlayerUtility and pass it areference to the observer class.3.Open the audio clip by calling CMdaAudioPlayerUtility::OpenFileL().4.WaituntilMMdaAudioPlayerCallback::MapcInitComplete() is called, with a result indicating either that the file hasbeen opened successfully, or that an error occurred.5.Call CMdaAudioPlayerUtility::Play() to start audio playback.6.When the audio has been played completely, or if an error occurs,MMdaAudioPlayerCallback::MapcPlayComplete() will becalled.7.Call CMdaAudioPlayerUtility::Close() to close the file. Ifyou don’t close the audio file, there will be a memory leak.MULTIMEDIA239You’ll see in the example code for the recipe that the CSimpleAudioPlayer class not only creates an instance of CMdaAudioPlayerUtility but also serves as observer, by derivation from MMdaAudioPlayerCallback.

Figure 4.7.2 shows a sequence diagram forthe steps above.CSimpleAudioPlayerCMdaAudioPlayerUtilityNewL()OpenFileL()MapcInitComplete()Play()MapcPlayComplete()Close()Figure 4.7.2 Sequence Diagram for Playing an Audio Clip from File, Showing the CMdaAudioPlayerUtility Class and the Client Class, which Implements the MMdaAudioPlayerCallback ObserverDiscussion: If your application has the MultimediaDD capability (seeChapter 3 for further discussion of platform security capabilities) you cansuccessfully override the default priority and priority preference parameters of the CMdaAudioPlayerUtility::NewL() method.

However,none of the examples in this book require this capability.Besides NewL(), class CMdaAudioPlayerUtility offers someother factory methods:• NewFilePlayerL(), to construct an audio player to play a filespecified by filename.• NewDesPlayerL(), to construct an audio player utility and playdata from a descriptor.• NewDesPlayerReadOnlyL(), to construct an audio player utilityand play from a read-only descriptor.Note that the three methods both open and initialize the audio clip. Itmeans MMdaAudioPlayerCallback::MapcInitComplete() willbe called once the initialization is complete. This is different from theNewL() method, because the latter does not initialize the audio playerutility, and requires a separate call to OpenFileL().

The OpenFileL()240SYMBIAN C++ RECIPESmethod opens an audio clip, which can either be specified by filenameor by passing a handle to the file.Note that we cannot play the file right after CMdaAudioPlayerUtility::OpenFileL() has returned. We have to wait until MMdaAudioPlayerCallback::MapcInitComplete() is called on theobserver.There are two other variants of open methods in CMdaAudioPlayerUtility:• OpenDesL(), to open an audio clip from a descriptor.• OpenUrlL(), to open an audio clip from a URL.What may go wrong when you do this: Note that not all devicessupport all variants of the OpenXyzL() methods. For example, S60devices don’t support OpenUrlL().Once the player utility has been initialized, we are able to start theaudio playback. It is done by calling CMdaAudioPlayerUtility::Play().

In most cases, you may want to adjust the volume before playinganything by calling CMdaAudioPlayerUtility::SetVolume().Tip: If you get an extraneous sound at the start of your audio clip, usethe SetVolumeRamp() function to get rid of it.Tip: The emulator normally supports only basic formats and codecs,such as AU and WAV. Other advanced formats and codecs, such asMP3, are currently not supported. This means you have to performtesting on the real devices.What may go wrong when you do this: Some audio clips may beprotected using digital rights management (DRM), in formats such asOMA DRM or WMDRM.

They cannot be played using CMdaAudioPlayerUtility.You can play DRM-protected files using a specific API for DRMprotected content, such as CDrmPlayerUtility in S60, which doesnot require the DRM capability.Alternatively, you can use the content access framework (CAF)to read DRM-protected files and pass them to MMF client APIs.Unfortunately, this requires your application to have DRM capability,which is one of the manufacturer-approved capabilities. It requires aMULTIMEDIA241high level of negotiation to win the trust of the phone manufacturerbefore they will grant it to you. For details of how to apply for theDRM capability, see www.symbiansigned.com.Further discussion of how to play DRM-protected files is outside thescope of this book.

However, you can find an example on the ForumNokia developer wiki, at wiki.forum.nokia.com/index.php/PlayingDRM-protected audio file using CDrmPlayerUtility.4.7.1.2Perform Basic Audio OperationsAmount of time required: 15 minutesLocation of example code: \Multimedia\AudioPlayingRequired libraries: mediaclientaudio.libRequired header file(s): MdaAudioSamplePlayer.hRequired platform security capability(s): NoneProblem: You want to do basic operations on the audio playback, suchas stop, play, rewind and fast forward.Solution: The CMdaAudioPlayerUtility class provides all methodsneeded to perform basic audio operations, such as:• Stop(), to stop audio playback.• Pause(), to pause audio playback.• SetPosition(), to set the current playback position from the startof the clip.• GetPosition(), to return the current playback position from thestart of the clip.Discussion: The audio playback can be stopped or paused at any time.

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

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

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

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