AVPlayer addPeriodicTimeObserverForInterval:queue:usingBlock: doesn't stop - ios

Description:
Our app is a music player app.
[AVPlayer addPeriodicTimeObserverForInterval:queue:usingBlock:]
We use this method to record the actual playing time of a user's song. Before it starts playing (and so does the single loop), we set the record time variable (playingSeconds) to 0 and keep +1 throughout the callback.
Normally, the method stops after a song is played.
But what we see in the background is that some users, a three-minute song, actually play for over 30,000 seconds (variable playingSeconds).
Question:
I just want to know what's causing the method to keep calling and not stop.
Or is there any other cause for this phenomenon?
Thanks!
#weakify(self);
self.playbackTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0)
queue:NULL
usingBlock:^(CMTime time) {
#strongify(self);
if (!self.flagSeeking) {
double ct = self.playerItem.currentTime.value / self.playerItem.currentTime.timescale;
if (self.totalDuration == 0) {
self.totalDuration = self.playerItem.duration.value / self.playerItem.duration.timescale;
[self updateNowPlayingInfo:YES];
}
if (ct <= self.totalDuration && self.currentTime != ct && !self.isBuffering) {
self.currentTime = ct;
}
if (self.state == BPAudioPlayerStatePlaying && !self.isBuffering) {
if (ct <= 0) {
self.playingSeconds = 0;
} else {
self.playingSeconds += 1;
}
}
}

Related

OrderClose function not working correctly

Is this the correct implementation of OrderClose()?
for(int ii = 0; ii < OrdersTotal(); ii++)
{
if(OrderSelect(ii, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType() == OP_BUY && OrderMagicNumber() == MagicStart && OrderSymbol() == symb)
{
int tikt = OrderTicket();
if(!OrderClose(tikt,OrderLots(),bid,4,clrPurple))
{
Print("Close Error", GetLastError());
}
}
if(OrderType() == OP_SELL && OrderMagicNumber() == MagicStart && OrderSymbol() == symb)
{
int tikt = OrderTicket();
if(!OrderClose(tikt,OrderLots(),ask,4,clrPurple))
{
Print("Close Error", GetLastError());
}
}
}
}
I am using this code right before opening a trade. For example, if there is a signal to buy then it closes the sell first and then opens a buy, and if there is a sell signal then it closes a sell first and then opens a buy.
But it only does this for the first time and wont work after that. Let's say there is a sell signal. Then it will close the buy and open the sell, but when there is a second signal for a buy then it won't close the sell neither will it open a buy.
There is no error in the experts tab. The only thing I receive in the experts tab is a message like this: Positions order mismatch. It does not appear like an error or a warning, it just appears as a message.
If you want to close all orders, you need to start iteration from the latest order position to the first position.
Try this:
for(int i = OrdersTotal()-1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS))
{
if(OrderType() == OP_BUY)
{
if(!OrderClose(OrderTicket(), OrderLots(), Bid, 0))
{
Print("Error closing order: ", GetLastError());
}
}
if(OrderType() == OP_SELL)
{
if(!OrderClose(OrderTicket(), OrderLots(), Ask, 0))
{
Print("Error closing order: ", GetLastError());
}
}
}
}
You shouldn't start iterating from 0 when you are closing orders, because OrdersTotal() function decrement its value while you loop through all orders and closing them one by one.
For example (in your loop) you have 5 orders:
i = 0, OrdersTotal() = 5 -> close order on position 0.
i = 1, OrdersTotal() = 4 -> close order on position 1.
i = 2, OrdersTotal() = 3 -> close order on position 2.
i = 3, and now loop is over, because i == OrdersTotal().
Additionally, instead of int tikt= OrderTicket();, just use OrderTicket() in OrderClose() function.
Try the following code which is more robust and does not assume the orders to be closed are of the same symbol of the chart the EA is running on. This will close all orders on the account. If you want to restrict this to orders that are on the chart the EA is running on, or orders only opened by the EA, you should use OrderSymbol() and OrderMagicNumber() to filter the orders before closing them.
if(OrdersTotal()>0)
{
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType()==OP_BUY || OrderType()==OP_SELL)
{
double price;
if(OrderType()==OP_BUY) price=MarketInfo(OrderSymbol(),MODE_BID); else price=MarketInfo(OrderSymbol(),MODE_ASK);
int ticket=OrderTicket();
bool res=OrderClose(ticket, OrderLots(), price, 50, clrNONE);
if(!res) Print("Error Closing Ticket #", IntegerToString(ticket));
}
else
{
int ticket=OrderTicket();
bool res=OrderDelete(ticket);
if(!res) Print("Error Closing Ticket #", IntegerToString(ticket));
}
}
}
}

How to calculate indicator buffer only once per day mql4

I have an indicator which gives one signal [Down Buffer]... I wish to only give signal once per day... Like after the first signal it will not paint any signal for the rest of the day! I have tested with below code it's now not painting at all?
//--- indicator buffers
double Buffer1[];
int day = 0;
int OnInit()
{
........................
}
int OnCalculate(......)
{
//--- main loop
for(int i = limit-1; i >= 0; i--)
{
//Indicator Buffer 1
if( here goes my condition )
{
if( day != Day() )
{
Buffer1[i] = High[i] + iATR(NULL, PERIOD_CURRENT, 14, i); //Set indicator value at Candlestick High + Average True Range
day = Day();
}
}
else
{
Buffer1[i] = EMPTY_VALUE;
}
}
return(rates_total);
}
What is wrong with my code? It's now not showing any signal at all...
Note : I have removed some of the code to make it simple...
Use the following function to check whether it is a new day.
It returns true if it is a new day, else returns false.
bool IsNewDay(){
static datetime prevDay = -1;
if( iTime(_Symbol, PERIOD_D1, 0) == prevDay ) return false;
prevDay = iTime(_Symbol, PERIOD_D1, 0);
return true;
}

Play interstitial ad every 3rd game in Swift

I've found an acceptable answer for Objective-C here:
Play interstitial ad every 3rd game
But, I'm trying to do the same thing in Swift. I'm looking how to write the Static variable.
Here's the Objective-C code:
static int count = 0;
-(void) GameOver {
if(count != 0 && count % 3 == 0)
[HZInterstitialAd show];
count++;
}
private var count = 0
func GameOver {
if (count != 0 && count % 3 == 0) {
HZInterstitialAd.show()
}
count++
}

FMOD_DSP_PITCHSHIFT doesn't work for mp3 on iOS

I was trying to implement a function to stretch the sound speed, without changing it's pitch and time scale.
I try the method to set the frequency of channel to slow of fast the speed.
Then use FMOD_DSP_PITCHSHIFT to correct the pitch sounds as default.
I was using wav format sound file for test and build function.
I'm trying to intergrate product resource which sound file was encoded as MP3.
PITCHSHIFT DSP doesn't work at MP3 sound channel. console log looks fine with no exception & error.
Same project and setting everything works fine in iOS Simulator.
After some research and experiments, results indicates even m4a works fine at iOS.
I wonder is this some kind of bug? or I missed something at configuration.
sample code was based on FMOD Sample project Play stream.
`/*==============================================================================
Play Stream Example
Copyright (c), Firelight Technologies Pty, Ltd 2004-2015.
This example shows how to simply play a stream such as an MP3 or WAV. The stream
behaviour is achieved by specifying FMOD_CREATESTREAM in the call to
System::createSound. This makes FMOD decode the file in realtime as it plays,
instead of loading it all at once which uses far less memory in exchange for a
small runtime CPU hit.
==============================================================================*/
#include "fmod.hpp"
#include "common.h"
int FMOD_Main()
{
FMOD::System *system;
FMOD::Sound *sound, *sound_to_play;
FMOD::Channel *channel = 0;
FMOD_RESULT result;
FMOD::DSP * pitch_shift;
unsigned int version;
void *extradriverdata = 0;
int numsubsounds;
Common_Init(&extradriverdata);
/*
Create a System object and initialize.
*/
result = FMOD::System_Create(&system);
ERRCHECK(result);
result = system->getVersion(&version);
ERRCHECK(result);
if (version < FMOD_VERSION)
{
Common_Fatal("FMOD lib version %08x doesn't match header version %08x", version, FMOD_VERSION);
}
result = system->init(32, FMOD_INIT_NORMAL, extradriverdata);
ERRCHECK(result);
result = system->createDSPByType(FMOD_DSP_TYPE_PITCHSHIFT, &pitch_shift);
ERRCHECK(result);
/*
This example uses an FSB file, which is a preferred pack format for fmod containing multiple sounds.
This could just as easily be exchanged with a wav/mp3/ogg file for example, but in this case you wouldnt need to call getSubSound.
Because getNumSubSounds is called here the example would work with both types of sound file (packed vs single).
*/
result = system->createSound(Common_MediaPath("aaa.m4a"), FMOD_LOOP_NORMAL | FMOD_2D, 0, &sound);
ERRCHECK(result);
result = sound->getNumSubSounds(&numsubsounds);
ERRCHECK(result);
if (numsubsounds)
{
sound->getSubSound(0, &sound_to_play);
ERRCHECK(result);
}
else
{
sound_to_play = sound;
}
/*
Play the sound.
*/
result = system->playSound(sound_to_play, 0, false, &channel);
ERRCHECK(result);
result = channel->addDSP(0, pitch_shift);
ERRCHECK(result);
float pitch = 1.f;
result = pitch_shift->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, pitch);
ERRCHECK(result);
pitch_shift->setActive(true);
ERRCHECK(result);
float defaultFrequency;
result = channel->getFrequency(&defaultFrequency);
ERRCHECK(result);
/*
Main loop.
*/
do
{
Common_Update();
if (Common_BtnPress(BTN_ACTION1))
{
bool paused;
result = channel->getPaused(&paused);
ERRCHECK(result);
result = channel->setPaused(!paused);
ERRCHECK(result);
}
if (Common_BtnPress(BTN_DOWN)) {
char valuestr;
int valuestrlen;
pitch_shift->getParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, &pitch, &valuestr, valuestrlen);
pitch+=0.1f;
pitch = pitch>2.0f?2.0f:pitch;
pitch_shift->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, pitch);
channel->setFrequency(defaultFrequency/pitch);
}
if (Common_BtnPress(BTN_UP)) {
char valuestr;
int valuestrlen;
pitch_shift->getParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, &pitch, &valuestr, valuestrlen);
pitch-=0.1f;
pitch = pitch<0.5f?0.5f:pitch;
pitch_shift->setParameterFloat(FMOD_DSP_PITCHSHIFT_PITCH, pitch);
channel->setFrequency(defaultFrequency/pitch);
}
result = system->update();
ERRCHECK(result);
{
unsigned int ms = 0;
unsigned int lenms = 0;
bool playing = false;
bool paused = false;
if (channel)
{
result = channel->isPlaying(&playing);
if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
{
ERRCHECK(result);
}
result = channel->getPaused(&paused);
if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
{
ERRCHECK(result);
}
result = channel->getPosition(&ms, FMOD_TIMEUNIT_MS);
if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
{
ERRCHECK(result);
}
result = sound_to_play->getLength(&lenms, FMOD_TIMEUNIT_MS);
if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE))
{
ERRCHECK(result);
}
}
Common_Draw("==================================================");
Common_Draw("Play Stream Example.");
Common_Draw("Copyright (c) Firelight Technologies 2004-2015.");
Common_Draw("==================================================");
Common_Draw("");
Common_Draw("Press %s to toggle pause", Common_BtnStr(BTN_ACTION1));
Common_Draw("Press %s to quit", Common_BtnStr(BTN_QUIT));
Common_Draw("");
Common_Draw("Time %02d:%02d:%02d/%02d:%02d:%02d : %s", ms / 1000 / 60, ms / 1000 % 60, ms / 10 % 100, lenms / 1000 / 60, lenms / 1000 % 60, lenms / 10 % 100, paused ? "Paused " : playing ? "Playing" : "Stopped");
Common_Draw("Pitch %02f",pitch);
}
Common_Sleep(50);
} while (!Common_BtnPress(BTN_QUIT));
/*
Shut down
*/
result = sound->release(); /* Release the parent, not the sound that was retrieved with getSubSound. */
ERRCHECK(result);
result = system->close();
ERRCHECK(result);
result = system->release();
ERRCHECK(result);
Common_Close();
return 0;
}
`
After some more experiments , i can approach the destination through switch sound file format to m4a on iOS Device.
MP3 still not working .

CocosDenshion: why isPlaying always false (I can hear the music)?

I have this:
-(ALuint)ID
{ return self.soundSource->_sourceId; }
-(void)play
{
[self.engine playSound:self.soundSource.soundId
sourceGroupId:0
pitch:self.pitch
pan:1.0
gain:1.0
loop:NO];
}
-(NSTimeInterval)duration
{ return durationOfSourceId(self.ID); }
-(NSTimeInterval)offset
{ return elapsedTimeOfSourceId(self.ID); }
-(BOOL)isPlaying
{
NSTimeInterval secondsRemaining = self.duration - self.offset;
NSLog(#"<%.3f>", self.soundSource.durationInSeconds);
NSLog(#"<%.3f> - <%.3f> = <%.3f> isPlaying <%i>", self.duration, self.offset, secondsRemaining, self.soundSource.isPlaying);
return (secondsRemaining > 0.0);
}
#pragma mark - OpenAL addons
static NSTimeInterval elapsedTimeOfSourceId(ALuint sourceID)
{
float result = 0.0;
alGetSourcef(sourceID, AL_SEC_OFFSET, &result);
return result;
}
static NSTimeInterval durationOfSourceId(ALuint sourceID)
{
//Thanks to http://stackoverflow.com/a/8822347
ALint bufferID, bufferSize, frequency, bitsPerSample, channels;
alGetSourcei(sourceID, AL_BUFFER, &bufferID);
alGetBufferi(bufferID, AL_SIZE, &bufferSize);
alGetBufferi(bufferID, AL_FREQUENCY, &frequency);
alGetBufferi(bufferID, AL_CHANNELS, &channels);
alGetBufferi(bufferID, AL_BITS, &bitsPerSample);
NSTimeInterval result = ((double)bufferSize)/(frequency*channels*(bitsPerSample/8));
return result;
}
Where engine is just an instance of CDSoundEngine. I really want to know when will the music stop. I'm into it for a whole day now, and I'm tired.
It logs:
[1445:707] <1.656>
[1445:707] <1.656> - <0.000> = <1.656> isPlaying <0>
So the OpenAL source ID is right (since I can get the duration).
The CDSoundSource is also right (since I can get the duration from that as well).
I can hear the sound playing.
But AL_SEC_OFFSET is always 0.0, isPlaying is always NO.
Why dont you get the state of the source and check if it is really being played?:
alGetSourcei(source, AL_SOURCE_STATE, &state);
return (state == AL_PLAYING);

Resources