Главная » Просмотр файлов » Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008

Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888), страница 34

Файл №779888 Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (Symbian Books) 34 страницаWiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888) страница 342018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The framework willcall PlayError() with KErrUnderflow as an error code when thishappens. PlayError() will also be called with KErrUnderflow whenthe last buffer is played. KErrUnderflow in this context means that theplaying operation has ended, either by marking the last buffer, or by notcalling PlayData() quickly enough. If the underflow error is not causedby the end of data, but is a genuine underflow, the best thing to do is torestart playing.void CAudioDemo::PlayError(TInt aError){if (aError == KErrUnderflow){// Play finished or stream not filled quickly enough}else{// Other error, handle here}}Calling the Stop() method of CMMFDevSound stops the audio streamwhile the stream is playing. Any data that has been passed into DevSoundvia PlayData() but not yet played will be thrown away.The advantage of using CMMFDevSound interface over other methodsis more flexibility and more control over some parameters.

It is the closestthing to what a game developer needs, in the absence of a dedicatedgame audio API.4.4 Background Music4.4.1 MIDI MusicThe most common way of supporting music in games has traditionallybeen through MIDI music. Because MIDI only stores the notes andinstruments in the music tracks, MIDI files are small and portable.Although the exact quality of the output depends on the MIDI engineand how the instruments are represented (by algorithms to generatesynthesized music, or by digitized samples of the original instrumentscontained in sound banks), the tunes in the music tracks are recognizableon all devices that support MIDI music.The ease of generating MIDI files is another big advantage for MIDImusic.

MIDI stands for ‘musical instrument digital interface’ and is theBACKGROUND MUSIC143standard method of communication between digital musical instruments.It is used to transfer and store the instrument players’ performanceinformation, so creating a MIDI file is as easy as playing notes on asynthesizer and capturing the output.Mobile phones first started using MIDI for polyphonic ringtones, whereseveral notes can be played at the same time.

Because of the specificrequirements of mobile devices, a special MIDI specification has beendeveloped called scaleable polyphony MIDI (SP-MIDI). SP-MIDI makesit possible to create scaleable content across devices with differentpolyphony. It allows the creator of the music to define channel priorityorder and masking, so that when the file is played on a device with lesspolyphony than the original track supports, only the channels markedby the composer will be suppressed. This way, the composer can createSP-MIDI files to support different levels of polyphony and can still controlthe downgrading of the quality in the music on lower-end devices.Besides supporting SP-MIDI, modern mobile phones now supportgeneral MIDI (G-MIDI), mobile extensible music format (Mobile XMF)and mobile downloadable sounds (Mobile DLS), as shown in Table4.2.

With SP-MIDI and G-MIDI, the instruments assigned to a specificprogram are fixed. Mobile DLS files are instrument definitions containingwavetable instrument sample data and articulation information such asenvelopes and loop points. It is generally used together with Mobile XMF,which is a format that contains both a SP-MIDI sequence and zero (ormore) Mobile DLS instrument sets.Table 4.2 MIDI formats supported in some current S60 and UIQ devicesMIDI/PhonesS60 3rd Ed. & S60 3rd Ed.FP1(Nokia N Series, E Series,6290, 3250, 5500)UIQ 3.0(Sony Ericsson M600,P1, P990, W950, W960)G-MIDISP-MIDI (with DLS)Mobile XMFMax.

Polyphony6440Symbian OS supports MIDI music through the CMidiClientUtility class, defined in midiclientutility.h. The usage of this class isvery similar to CMdaAudioPlayerUtility. This class contains methods to play MIDI sequences stored in SMF (type 0 and type 1) and XMFfiles as well as descriptors. It also allows playing of single notes, openingup the possibility of creating dynamic music. The observer mixin class toimplement is MMidiClientUtilityObserver.144ADDING AUDIO TO GAMES ON SYMBIAN OSclass CAudioDemo : public CActive, MMidiClientUtilityObserver{public:virtual void MmcuoStateChanged(TMidiState aOldState,TMidiState aNewState,const TTimeIntervalMicroSeconds& aTime,TInt aError);virtual void MmcuoTempoChanged(TInt aMicroBeatsPerMinute);virtual void MmcuoVolumeChanged(TInt aChannel,TReal32 aVolumeInDecibels);virtual void MmcuoMuteChanged(TInt aChannel, TBool aMuted);virtual void MmcuoSyncUpdate(const TTimeIntervalMicroSeconds&aMicroSeconds, TInt64 aMicroBeats);virtual void MmcuoMetaDataEntryFound(const TInt aMetaDataEntryId,const TTimeIntervalMicroSeconds& aPosition);virtual void MmcuoMipMessageReceived(constRArray<TMipMessageEntry>& aMessage);virtual void MmcuoPolyphonyChanged(TInt aNewPolyphony);virtual void MmcuoInstrumentChanged(TInt aChannel, TInt aBankId,TInt aInstrumentId);private:CMidiClientUtility* iMidiUtil;};Construction is similar to the CMdaAudioPlayerUtility class.Priority and priority preference parameters are supplied to the staticNewL() factory method together with the observer.void CAudioDemo::ConstructL(){iMidiUtil = CMidiClientUtility::NewL(*this, EMdaPriorityNormal,EMdaPriorityPreferenceTime);}There are different ways to use this class to manipulate the MIDIengine.

It can be used to play a MIDI file, to play individual notes or to doboth at the same time. To play a MIDI file by itself, a call to OpenFile()method to open the file is required as the first step.void CAudioDemo::OpenMidiL(){_LIT(KFile, "c:\\private\\E482B27E\\empire.mid");iMidiUtil->OpenFile(KFile);...}The MIDI engine is a state machine running in an active schedulerloop, and OpenFile() will kick off a state transition of the enginefrom closed to open state. All state transitions will complete by callingMmcuoStateChanged() and pass the old and the new states.

By usingthese two state variables, it is possible to handle the state transitions.BACKGROUND MUSIC145void CAudioDemo::MmcuoStateChanged(TMidiState aOldState,TMidiState aNewState,const TTimeIntervalMicroSeconds& aTime, TInt aError){if (aError == KErrNone){if ((aOldState == EClosed)&&(aNewState == EOpen)){// open finished}else if ((aOldState == EPlaying)&&(aNewState == EOpenEngaged)){// play finished}...}else{// Other error, handle here}}After OpenFile() is called, the engine will be in EOpen state, readyfor playing. Calling Play() method will start playing the MIDI file.void CAudioDemo::PlayMidiL(){...iMidiUtil->Play();...}During the playing of the MIDI file, the framework will call otherobserver callbacks, like tempo or volume change, as well.

Calling Stop()stops playing of the MIDI file.void CAudioDemo::PlayMidiL(){...TTimeIntervalMicroSeconds fadeOutDuration(2000000);iMidiUtil->Stop(fadeOutDuration);...}One important thing to note here is that the end state of the MIDIengine will differ according to the state the engine was in when themethod was called. This is also true for other state-changing methods likeOpen() and Play(). Therefore, it is necessary to detect state transitionsin MmcuoStateChanged() rather than relying only on the end state.The second way of using this engine is its capability of processingindividual MIDI messages to generate audio on the fly. This is especially useful when combined with the MIDI resource playing capability.146ADDING AUDIO TO GAMES ON SYMBIAN OSGenerating MIDI messages in real time allows the triggering of soundeffects on one or more MIDI channels set aside for that purpose, whilethe background music is playing on a separate channel, effectively usingthe MIDI engine as a software mixer.One other potential use of this capability is the ability to change certainengine parameters on the fly, which opens up the possibility of creatingdynamic music.

It is possible to have a single music composition that canbe played with one set of instruments and a specific tempo to create a ‘sad’tune, yet played with a different set of instruments and a different tempoto create a ‘happy’ tune. With the ability to change tempo, instruments,and other parameters on the fly using the CMidiClientUtility API,it is possible to make dynamic music transitions in response to in-gameevents.The simplest way to use the MIDI engine in real time is to playindividual notes by calling the PlayNoteL() method. The MIDI enginemust be in a state where it is processing MIDI events (EOpenEngaged,EOpenPlaying or EClosedEngaged) prior to sending the notes.

Thereare other prerequisites as well. The channel on which the note willbe played needs to have an instrument, and the channel volume (aswell as the general volume of the engine) must be set to an audiblelevel. Otherwise, even if the function call succeeds, no sound will beheard.TInt maxVol;maxVol = iMidiUtil->MaxVolumeL();iMidiUtil->SetVolumeL(maxVol); // overall volume of the MIDI engineset to maximumiMidiUtil->Play(); // MIDI engine starts processing events...// Wait for MIDI engine to transition to an event processing state// in MmcuoStateChanged...iMidiUtil->SetInstrumentL(1, 0x3C80, 17); // Instrument 17 (DrawbarOrgan) in bank 0x3C80 is set on channel 1// Maximum channel volume in 32-bit real formatTReal32 maxVol = iMidiUtil->MaxChannelVolumeL();// Set volume of channel 1 to maximumiMidiUtil->SetChannelVolumeL(1, maxVol);...// Wait for MIDI engine to receive the callback to MmcuoVolumeChanged// to make sure MIDI engine processed volume change event...TTimeIntervalMicroSeconds duration(1000000);iMidiUtil->PlayNoteL(1, 60, duration, 64, 64); //play middle C on// channel 1 for 1 second at average velocityCalling the Close() method is required for cleanup when the MIDIengine is no longer needed (for example, if there is no music mode in agame, or during application exit prior to destruction).BACKGROUND MUSIC147void CAudioDemo::PlayMidiL(){...iMidiUtil->Close();}The CMidiClientUtility class supports a wealth of methods forMIDI event and message processing (SendMessageL(), SendMipMessageL(), CustomCommandAsync(), CustomCommandSyncL()),custom bank manipulation (LoadCustomBankL(), LoadCustomInstrumentL(), descriptor versions, associated query and unloadmethods), play control (SetPitchTranspositionL(), SetPlaybackRateL(), SetPositionMicroBeatsL()), and many more.The details of this class are beyond the scope of this book, but gamedevelopers are strongly encouraged to read more about this class in theSymbian OS Library, which is part of the SDK, to find out how they canuse it effectively in their game audio engines.4.4.2 Digitized Music Streaming Using the Software MixerA more expensive alternative to MIDI for playing background game musicis to play digitized music.

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

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

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

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