Search Results

Search found 122 results on 5 pages for 'avaudioplayer'.

Page 5/5 | < Previous Page | 1 2 3 4 5 

  • Finding out estimated duration of a stream using Core Audio

    - by Reflog
    I am streaming a MP3 over network using custom feeding code, not AVAudioPlayer (which only works with URLs) using APIs like AudioFileStreamOpen and etc. Is there any way to estimate a length of the stream? I know that I can get a 'elapsed' property using: if(AudioQueueGetCurrentTime(queue.audioQueue, NULL, &t, &b) < 0) return 0; return t.mSampleTime / dataFormat.mSampleRate; But what about total duration to create a progress bar? Is that possible?

    Read the article

  • Listening to the iPhone mic with SCListener and playing music at the same time: how?

    - by Eamon Ford
    Hello, I am using Stephen Celis' SCListener class (for iPhone) to "listen" from the microphone, but I also need to be playing music at the same time using the MediaPlayer framework. However, when I start listening with SCListener, the music fades out and stops. I have set the kAudioSessionCategory_PlayAndRecord property on the audio session in SCListener, which should allow me to play audio and record audio at the same time, but as far as I can tell it has no effect. I'm confused, because according to other developers' results, this works just fine, but not for me. I'm thinking maybe the kAudioSessionCategory_PlayAndRecord property allows you to play sound and record if you're using the AVAudioPlayer framework or something to play the sound, but maybe not the MediaPlayer framework? This would be a problem for me because I need to play music from the user's iPod library, which, as far as I know is only possible to do using the MediaPlayer framework. Does anyone know how I can get around this problem? Thanks in advance!

    Read the article

  • Microphone audio streaming from Cocoa mac app to iPhone

    - by Benzamin
    Hi devs, I'm trying to build a microphone audio streamer to iPhone. The server software will be a mac desktop app and the client will be iPhone, and they are connected via tcp port. I've successfully connected the mac app and iPhone, and tried to send a fixed test.m4a audio file first. But at the iPhone i grabbed the data well, when tried to play it i used AVAudioPlayer and its returning OSStatus error. I played around with the audio queue service but its very tricky and i only got some example for fixed length audio playing like http://cocoawithlove.com/2009/06/revisiting-old-post-streaming-and.html Now i need help on two things, how can i continuously grab audio data from Mac desktop microphone? And then after grabbing the data how i can play this unfixed length audio data in the iPhone. What exactly i need to do? Please please help me on this......

    Read the article

  • Pre-crash iphone symptoms - odd user position, volume change

    - by BankStrong
    I'm seeing intermittent strange symtoms in my app: Blue blob (user position in MKMapView) starts "exploding" (odd, jerky animation). Can begin at startup and seems to indicate eventual problems. Speaker volume suddenly increases (back to level before I invoked kAudioSessionSetProperty_OtherMixableAudioShouldDuck). The app keeps running, but this change tells me to expect no more sounds from AVAudioPlayer. Also a reliable indicator of a future crash (on save, etc). I'm having trouble provoking this in the debugger (seems to only happen with movement in GPS). Any ideas to track it down?

    Read the article

  • iPhone game audio and background music

    - by Boon
    Have a few questions related to adding sounds to my game, specifically intro music (for splash), background music (loop) and button event sounds. Hope you can share your knowledge on this. 1) Should I use compressed sounds or uncompressed sounds? Or perhaps a combination of the two? Are there any limitations on the iPhone hardware that I should be aware of -- for example, the ability to play multiple compressed sounds? 2) What's the best audio format for my purpose? 3) For background music, I am thinking of using AVAudioPlayer. For button event sounds, I am thinking of using AudioServicesPlaySystemSound, what do you think? 4) Any other issues I should be aware of? Thank you!

    Read the article

  • AVAudioRecorder prepareToRecord works, but record fails

    - by iPadDeveloper2011
    I just built and tested a basic AVAudioRecorder/AVAudioPlayer sound recorder and player. Eventually I got this working on the device, as well as the simulator. My player/recorder code is in a single UIView subclass. Unfortunately, when I copy the class into my main project, it no longer works (on the device--the simulator is fine). prepareToRecord is working fine, but record isn't. Here is some code: audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error]; if ([audioRecorder prepareToRecord]){ audioRecorder.meteringEnabled = YES; if(![audioRecorder record])NSLog(@"recording failed!"); }else { int errorCode = CFSwapInt32HostToBig ([error code]); NSLog(@"preparedToRecord=NO Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode); ... I get "recording failed". Anyone have any ideas why this is happening?

    Read the article

  • Is it possible to have a sound play before/during the splash screen?

    - by Jeff
    My app takes a few seconds to load and I have a splash screen. Once "viewDidLoad" I have a little sound play. I feel that the sound would be in better use if it started playing when the splash screen popped up. Is it possible to have a sound start before/during the splash screen? Here is my code: (under viewDidLoad) NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"intorSound" ofType: @"aif"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil]; [player setVolume: soundVolumeValue]; // available range is 0.0 through 1.0 [player play]; [fileURL release]; Thank you for your time!

    Read the article

  • How to convert code to properly release memory

    - by BankStrong
    I've taken over a code base that has subtle flaws - audio player goes mute, unlogged crashes, odd behavior, etc. I found a way to provoke one instance of the problem and tracked it to this code snippet: NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[[soundsToPlay objectAtIndex:count] description] ofType:@"mp3"]]; self.audioPlayer = nil; self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil]; self.audioPlayer.delegate = self; AudioSessionSetActive(YES); [audioPlayer play]; When I comment out the 2nd line (nil) and add a release to the end, this problem stops. [self.audioPlayer release]; Where do I go from here? Nils are used in a similar fashion throughout the code (and may cause similar problems) - is there a safe way to remove them? I'm new to memory management - how can I discern proper nil usage from bad nil usage?

    Read the article

  • How to download a wav file from the web to a location on iPhone using NSFileHandle and NSURLConnecti

    - by Jinru
    Hi all, I want to download a wav file from a web service, cache it on the iphone and playback it using AVAudioPlayer. Using NSFileHandle and NSURLConnection seems a viable solution when dealing with relatively large files. However, after running the app in the simulator I don't see any saved file under the defined directory (NSHomeDirectory/tmp). Below is my basic code. Where am I doing wrong? Any thoughts are appreciated! #define TEMP_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] - (void)downloadToFile:(NSString*)name { NSString* filePath = [[NSString stringWithFormat:@"%@/%@.wav", TEMP_FOLDER, name] retain]; self.localFilePath = filePath; // set up FileHandle self.audioFile = [[NSFileHandle fileHandleForWritingAtPath:localFilePath] retain]; [filePath release]; // Open the connection NSURLRequest* request = [NSURLRequest requestWithURL:self.webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; } #pragma mark - #pragma mark NSURLConnection methods - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data { [self.audioFile writeData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error { NSLog(@"Connection failed to downloading sound: %@", [error description]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; [audioFile closeFile]; }

    Read the article

  • Using kAudioSessionProperty_OtherMixableAudioShouldDuck on iPhone

    - by Cliff
    Hello, I'm trying to get consistant behavior out of the kAudioSessionProperty_OtherMixableAudioShouldDuck property on the iPhone to allow iPod music blending and I'm having trouble. At the start of my app I set an Ambient category like so: -(void) initialize { [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil]; } Later on when I attempt to play audio I set the duck property using the following method: //this will crossfade the audio with the ipod music - (void) toggleCrossfadeOn:(UInt32)onOff { //crossfade the ipod music AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck,sizeof(onOff),&onOff); AudioSessionSetActive(onOff); } I call this passing a numeric "1" just before playing audio like so: [self toggleCrossfadeOn:1]; [player play]; I then call the crossfade method again passing a zero when my app's audio completes using a playback is stopping callback like so: -(void) playbackIsStoppingForPlayer:(MQAudioPlayer*)audioPlayer { NSLog(@"Releasing player"); [audioPlayer release]; [self toggleCrossfadeOn:0]; } In my production app this exact code works as expected, causing the ipod to fade out just before playing my app's audio then fade back in when the audio finishes playing. In a new project I recently started, I get different behavior. The iPod audio fades down and never fades back in. In my production app I use the AVAudioPlayer where in my new app I've written a custom audio player that uses audio queues. Could somebody help me understand the differences and how to properly use this API?

    Read the article

  • displaying music current time & duration from AVFoundation

    - by msb
    I have a view-based iphone application that has a single play-pause button that plays an mp3 file. At the time of invoking my doPlayPauseButton() method, I 'd like to show the current time and total duration of this mp3 through the AVAudioPlayer instance I've created, called myAudioPlayer. I have placed two labels at the UI and i'm trying to assign the currentTime and duration properties to these label when the playing begins but my attempts have failed. Here's my play/pause loop, any help would be appreciated: -(IBAction) doPlayPauseButton:(UIButton *)theButton { if(myAudioPlayer.playing) { [myActivityIndicatorView stopAnimating]; myActivityIndicatorView.hidden = YES; //I think I need a myAudioPlayer.currentTime call of some sort for my labels. [myAudioPlayer pause]; [theButton setTitle:@"Play" forState:UIControlStateNormal]; [myTimer invalidate]; } else { [myActivityIndicatorView startAnimating]; myActivityIndicatorView.hidden = NO; myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doTimer) userInfo:nil repeats:YES]; [myAudioPlayer play]; [theButton setTitle:@"Pause" forState:UIControlStateNormal];

    Read the article

  • iPhone - Memory Management - Using Leaks tool and getting some bizarre readings.

    - by Robert
    Hey all, putting the finishing touches on a project of mine so I figured I would run through it and see if and where I had any memory leaks. Found and fixed most of them but there are a couple of things regarding the memory leaks and object alloc that I am confused about. 1) There are 2 memory leaks that do not show me as responsible. There are 8 leaks attributed to AudioToolbox with the function being RegisterEmbeddedAudioCodecs(). This accounts for about 1.5 kb of leaks. The other one is detected immediately when the app begins. Core Graphics is responsible with the extra info being open_handle_to_dylib_path. For the audio leak I have looked over my audio code and to me it seems ok. self.musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:songFilePath] error:NULL]; [musicPlayer prepareToPlay]; [musicPlayer play] is called later on in a function. 2) Is it normal for there to be a spike in Object Allocation whenever a new view or controller is presented? My total memory usage is very, very low except for whenever I present a view controller. It spikes then immediately goes back down. I am guessing that this is just the phone handling all the information for switching or something. Blegh. Wall of text. Thanks in advance to anyone who helps! =)

    Read the article

  • How can I implement a volume meter for a song currently playing? (iPhone OS 3.1.3)

    - by Adam
    Hi i'm very new to core audio and I just would like some help in coding up a little volume meter for whatever's being outputted through headphones or built-in speaker. Like a dB meter. I have the following code, and have been trying to go through the apple source project "SpeakHere", but it's a nightmare trying to go through all that, without knowing how it works first... Could anyone shed some light? Here's the code I have so far... (void)displayWaveForm { while (musicIsPlaying == YES { NSLog(@"%f",sizeof(AudioQueueLevelMeterState)); } } (IBAction)playMusic { if (musicIsPlaying == NO) { NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/track7.wav",[[NSBundle mainBundle] resourcePath]]]; NSError *error; music = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; music.numberOfLoops = -1; music.volume = 0.5; [music play]; musicIsPlaying = YES; [self displayWaveForm]; } else { [music pause]; musicIsPlaying = NO; } }

    Read the article

  • Play Multiple iPod Library Songs On iPhone At The Same Time With Pitch Bending & Other Effects

    - by Dino
    Hi, I have been going at this for the past two weeks and it is driving me crazy. I asked this question a couple of days ago (Extract iPod Library raw PCM samples and play with sound effects) and whilst the answer got me half way there I am still stuck. Basically what I am trying to achieve is load up multiple songs from the iPod library for playback with effects such as pitch bend, eq effects etc... I have gone down the route of AVPlayer and AVAudioPlayer which are too simple. The only framework I've seen that can play audio with these effects is OpenAL. I have tried a few objective c wrappers (Finch and ObjectAL) Finch does not play compressed audio whilst ObjectAL will only convert it for me if I pass in a URL for the file (which is something I cannot do because I only have an incompatible iPod library URL). An example of an app that does what I want beautifilly is Tap DJ. It can load up songs from the iPod library fast (unlike TouchDJ and it plays them with all sorts of effects. Any help would be much appreciated.

    Read the article

  • Calling a method from another view in objective-c. (iphone sdk).

    - by MarcZero
    Hello. I am currently creating a multi-view game on the iPhone platform. I have my main view start to play some background music upon loading. I then go to another view and start the game. I am trying to get the background music from the original view to stop once I start the game. I am having trouble getting the stop playing music message to my original view. Here is the relevant info: The main view where the sound is played from is just a subView of the programViewController class called *viewController. The heading is in the programAppDelegate class. The sound is done using the AVAudioPlayer class and plays fine when the program starts up and when I navigate to other subviews that are added on by going through the menu system. In the view that I want to start the game, I attempt to call the instance of the class to turn of the player but anytime I use this format of code: [viewController #######]; It gives a build error of "viewController undeclared" no matter what I put after the "viewController" in the message.I have attempted to import the programAppDelegate.h file but it still gives the same error. I realize this might be a simple misunderstanding of the objective-c language but I cannot find any info on this issue. I am a recent convert from Java so I am trying to wrap my head around everything. Thank you for your time!

    Read the article

  • Playing a sequence of sounds without gaps (iPhone)

    - by Fiire
    I thought maybe the fastest way was to go with Sound Services. It is quite efficient, but I need to play sounds in a sequence, not overlapped. Therefore I used a callback method to check when the sound has finished. This cycle produces around 0.3 seconds in lag. I know this sounds very strict, but it is basically the main axis of the program. EDIT: I now tried using AVAudioPlayer, but I can't play sounds in a sequence without using audioPlayerDidFinishPlaying since that would put me in the same situation as with the callback method of SoundServices. EDIT2: I think that if I could somehow get to join the parts of the sounds I want to play into a large file, I could get the whole audio file to sound continuously. EDIT3: I thought this would work, but the audio overlaps: waitTime = player.deviceCurrentTime; for (int k = 0; k < [colores count]; k++) { player.currentTime = 0; [player playAtTime:waitTime]; waitTime += player.duration; } Thanks

    Read the article

  • How to program a real-time accurate audio sequencer on the iphone?

    - by Walchy
    Hi... I want to program a simple audio sequencer on the iphone but I can't get accurate timing. The last days I tried all possible audio techniques on the iphone, starting from AudioServicesPlaySystemSound and AVAudioPlayer and OpenAL to AudioQueues. In my last attempt I tried the CocosDenshion sound engine which uses openAL and allows to load sounds into multiple buffers and then play them whenever needed. Here is the basic code: init: int channelGroups[1]; channelGroups[0] = 8; soundEngine = [[CDSoundEngine alloc] init:channelGroups channelGroupTotal:1]; int i=0; for(NSString *soundName in [NSArray arrayWithObjects:@"base1", @"snare1", @"hihat1", @"dit", @"snare", nil]) { [soundEngine loadBuffer:i fileName:soundName fileType:@"wav"]; i++; } [NSTimer scheduledTimerWithTimeInterval:0.14 target:self selector:@selector(drumLoop:) userInfo:nil repeats:YES]; In the initialisation I create the sound engine, load some sounds to different buffers and then establish the sequencer loop with NSTimer. audio loop: - (void)drumLoop:(NSTimer *)timer { for(int track=0; track<4; track++) { unsigned char note=pattern[track][step]; if(note) [soundEngine playSound:note-1 channelGroupId:0 pitch:1.0f pan:.5 gain:1.0 loop:NO]; } if(++step>=16) step=0; } Thats it and it works as it should BUT the timing is shaky and instable. As soon as something else happens (i.g. drawing in a view) it goes out of sync. As I understand the sound engine and openAL the buffers are loaded (in the init code) and then are ready to start immediately with alSourcePlay(source); - so the problem may be with NSTimer? Now there are dozens of sound sequencer apps in the appstore and they have accurate timing. I.g. "idrum" has a perfect stable beat even in 180 bpm when zooming and drawing is done. So there must be a solution. Does anybody has any idea? Thanks for any help in advance! Best regards, Walchy

    Read the article

  • Memory issues - Living vs. overall -> app is killed

    - by D33
    I'm trying to check my applications memory issues in Instruments. When I load the application I play some sounds and show some animations in UIImageViews. To save some memory I load the sounds only when I need it and when I stop playing it I free it from the memory. problem 1: My application is using about 5.5MB of Living memory. BUT The Overall section is growing after start to 20MB and then it's slowly growing (about 100kB/sec). But responsible Library is OpenAL (OAL::Buffer), dyld (_dyld_start)-I am not sure what this really is, and some other stuff like ft_mem_qrealloc, CGFontStrikeSetValue, … problem 2: When the overall section breaks about 30MB, application crashes (is killed). According to the facts I already read about overall memory, it means then my all allocations and deallocation is about 30MB. But I don't really see the problem. When I need some sound for example I load it to the memory and when I don't need it anymore I release it. But that means when I load 1MB sound, this operation increase overall memory usage with 2MB. Am I right? And when I load 10 sounds my app crashes just because the fact my overall is too high even living is still low??? I am very confused about it. Could someone please help me clear it up? (I am on iOS 5 and using ARC) SOME CODE: creating the sound OpenAL: MYOpenALSound *sound = [[MyOpenALSound alloc] initWithSoundFile:filename willRepeat:NO]; if(!sound) return; [soundDictionary addObject:sound]; playing: [sound play]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, ((sound.duration * sound.pitch) + 0.1) * NSEC_PER_SEC), dispatch_get_current_queue(), ^{ [soundDictionary removeObjectForKey:[NSNumber numberWithInt:soundID]]; }); } creating the sound with AVAudioPlayer: [musics replaceObjectAtIndex:ID_MUSIC_MAP withObject:[[Music alloc] initWithFilename:@"mapMusic.mp3" andWillRepeat:YES]]; pom = [musics objectAtIndex:musicID]; [pom playMusic]; and stop and free it: [musics replaceObjectAtIndex:ID_MUSIC_MAP withObject:[NSNull null]]; AND IMAGE ANIMATIONS: I load images from big PNG file (this is realated also to my other topic : Memory warning - UIImageView and its animations) I have few UIImageViews and by time I'm setting animation arrays to play Animations... UIImage *source = [[UIImage alloc] initWithCGImage:[[UIImage imageNamed:@"imageSource.png"] CGImage]]; cutRect = CGRectMake(0*dimForImg.width,1*dimForImg.height,dimForImg.width,dimForImg.height); image1 = [[UIImage alloc] initWithCGImage:CGImageCreateWithImageInRect([source CGImage], cutRect)]; cutRect = CGRectMake(1*dimForImg.width,1*dimForImg.height,dimForImg.width,dimForImg.height); ... image12 = [[UIImage alloc] initWithCGImage:CGImageCreateWithImageInRect([source CGImage], cutRect)]; NSArray *images = [[NSArray alloc] initWithObjects:image1, image2, image3, image4, image5, image6, image7, image8, image9, image10, image11, image12, image12, image12, nil]; and this array I just use simply like : myUIImageView.animationImages = images, ... duration -> startAnimating

    Read the article

  • Can't record or play with a simple recorder?

    - by user1280535
    I have 2 classes, a record and a player. In my main scene, I create an instance of them and play and record. But, as I see, it only records and somehow does not play (the file is not there!) Here is the code for both : -(void)record { NSArray *dirPaths; NSString *docsDir; NSString *sound= @"sound0.caf" ; dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ; docsDir = [dirPaths objectAtIndex:0]; NSString *soundFilePath = [docsDir stringByAppendingPathComponent:sound]; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0], AVSampleRateKey, [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey, [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey, nil]; NSError *error; myRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:settings error:&error]; if (myRecorder) { NSLog(@"rec"); [myRecorder prepareToRecord]; myRecorder.meteringEnabled = YES; [myRecorder record]; } else NSLog( @"error" ); } I can see the log of rec. -(void)play { NSArray *dirPaths; NSString *docsDir; dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; NSString *soundFilePath1 = @"sound0.caf" ; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath1]; BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:soundFilePath1]; if(isMyFileThere) { NSLog(@"PLAY"); avPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:NULL]; avPlayer1.volume = 8.0; avPlayer1.delegate = self; [avPlayer1 play]; } } I DONT SEE THE LOG OF PLAY ! I call them both with: recInst=[recorder alloc]; //to rec [recInst record]; plyInst=[player alloc]; //play [plyInst play]; and to stop the recorder: - (void)stopRecorder { NSLog(@"stopRecordings"); [myRecorder stop]; //[myRecorder release]; } What's wrong here? Thanks.

    Read the article

  • How to disable multiple touches on a ScrollView and UIImage

    - by Rob
    I have a scrollview that I am loading images into that the user can touch and play a sound. However, the program is getting confused when I press one image with one finger and then another one with a different finger. It thinks you are pushing the same button again and therefore plays the sound again (so you have two of the same sounds playing at the same time even though you may have pressed a different sound button). I tried setting exclusiveTouch for each UIImage but that didn't seem to work in this case for some reason. What am I missing or is there a better way to do this? Here is some code: for creating buttons.... - (void) createButtons { CGRect myFrame = [self.outletScrollView bounds]; CGFloat gapX, gapY, x, y; int columns = 3; int myIndex = 0; int viewWidth = myFrame.size.width; int buttonsCount = [g_AppsList count]; float actualRows = (float) buttonsCount / columns; int rows = buttonsCount / columns; int buttonWidth = 100; int buttonHeight = 100; if (actualRows > rows) rows++; //set scrollview content size to hold all the glitter icons library gapX = (viewWidth - columns * buttonWidth) / (columns + 1); gapY = gapX; y = gapY; int contentHeight = (rows * (buttonHeight + gapY)) + gapY; [outletScrollView setContentSize: CGSizeMake(viewWidth, contentHeight)]; UIImage* myImage; NSString* buttonName; //center all buttons to view int i = 1, j = 1; for (i; i <= rows; i++) { //calculate gap between buttons gapX = (viewWidth - (buttonWidth * columns)) / (columns + 1); if (i == rows) { //this is the last row, recalculate gap and pitch gapX = (viewWidth - (buttonWidth * buttonsCount)) / (buttonsCount + 1); columns = buttonsCount; }//end else x = gapX; j = 1; for (j; j <= columns; j++) { //get shape name buttonName = [g_AppsList objectAtIndex: myIndex]; buttonName = [NSString stringWithFormat: @"%@.png", buttonName]; myImage = [UIImage imageNamed: buttonName]; TapDetectingImageView* imageView = [[TapDetectingImageView alloc] initWithImage: myImage]; [imageView setFrame: CGRectMake(x, y, buttonWidth, buttonHeight)]; [imageView setTag: myIndex]; [imageView setContentMode:UIViewContentModeScaleToFill]; [imageView setUserInteractionEnabled: YES]; [imageView setMultipleTouchEnabled: NO]; [imageView setExclusiveTouch: YES]; [imageView setDelegate: self]; //add button to current view [outletScrollView addSubview: imageView]; [imageView release]; x = x + buttonWidth + gapX; //increase button index myIndex++; }//end for j //increase y y = y + buttonHeight + gapY; //decrease buttons count buttonsCount = buttonsCount - columns; }//end for i } and for playing the sounds... - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //stop playing theAudio.stop; // cancel any pending handleSingleTap messages [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(handleSingleTap) object:nil]; UITouch* touch = [[event allTouches] anyObject]; NSString* filename = [g_AppsList objectAtIndex: [touch view].tag]; NSString *path = [[NSBundle mainBundle] pathForResource: filename ofType:@"m4a"]; theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; theAudio.delegate = self; [theAudio prepareToPlay]; [theAudio setNumberOfLoops:-1]; [theAudio setVolume: g_Volume]; [theAudio play]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { BOOL allTouchesEnded = ([touches count] == [[event touchesForView:self] count]); if (allTouchesEnded) { //stop playing theAudio.stop; }//end if //stop playing theAudio.stop; }

    Read the article

  • Memory management in iphone cocos2d

    - by muthu
    i am iphone developer very new to this field....i am developing a ebook app in iphone using cocos2d...i use more than 150 images(i guess) the problem while turning from one page to another images get hanged randomly...... i tried this also [[TextureMgr sharedTextureMgr] removeAllTextures]; but went in vain...i guess the the problem is with the memory.....this my coding for all the pages -(id)init { if( (self=[super init] )) { self.isTouchEnabled = YES; [SimpleAudioEngine sharedEngine]; NSLog(@"b4 cover"); Sprite *bg1 = [Sprite spriteWithFile:@"a.jpg"]; bg1.anchorPoint = CGPointZero; [self addChild:bg1 z:-1]; once = TRUE; soundId = [[SimpleAudioEngine sharedEngine] playEffect:@".mp3"]; } return self; } -(void) transitionfront:(id) sender { [[SimpleAudioEngine sharedEngine] stopEffect:soundId]; soundId1 = [[SimpleAudioEngine sharedEngine] playEffect:@"page_turn.mp3"]; flip = [[Sprite spriteWithFile:@"a.jpg"] retain]; [self addChild: flip z:1]; [flip setPosition:ccp(160,240)]; Animation* animation1 = [Animation animationWithName:@"Page1" delay:0.09]; for( int i=1;i<4;i++) [animation1 addFrameWithFilename: [NSString stringWithFormat:@".jpg", i]]; id action = [Animate actionWithAnimation: animation1]; //id action = [RepeatForever actionWithAction:[Animate actionWithAnimation: animation1]]; [flip runAction:action]; [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(moveforward) userInfo:nil repeats:NO]; } -(void) moveforward { [[SimpleAudioEngine sharedEngine] stopEffect:soundId1]; [[Director sharedDirector] replaceScene: [ [Scene node] addChild: [nextpage node] z:0] ]; } -(void) transitionback:(id) sender { [[SimpleAudioEngine sharedEngine] stopEffect:soundId]; soundId1 = [[SimpleAudioEngine sharedEngine] playEffect:@".mp3"]; flip = [[Sprite spriteWithFile:@".jpg"] retain]; [self addChild: flip z:1]; [flip setPosition:ccp(160,240)]; Animation* animation1 = [Animation animationWithName:@"Page1" delay:0.09]; for( int i=3;i>0;i--) [animation1 addFrameWithFilename: [NSString stringWithFormat:@".jpg", i]]; id action = [Animate actionWithAnimation: animation1]; //id action = [RepeatForever actionWithAction:[Animate actionWithAnimation: animation1]]; [flip runAction:action]; [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(movebackward) userInfo:nil repeats:NO]; } -(void) movebackward{ //[[SimpleAudioEngine sharedEngine]stopEffect:@".mp3"]; [[Director sharedDirector]replaceScene:[[Scene node]addChild:[b4page node] z:0]]; } -(void) glossary :(id) sender { [[SimpleAudioEngine sharedEngine]stopEffect:soundId]; [[Director sharedDirector]replaceScene:[[Scene node]addChild:[ node] z:0]]; } -(BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint cocosTouchPoint = [touch locationInView: [touch view]]; CGPoint point = [[Director sharedDirector] convertToGL:cocosTouchPoint]; NSLog(@"pointx: %f pointy:%f", point.x, point.y); // Was a tab touched, if so, which one... if (CGRectContainsPoint(CGRectMake(220, 0, 100, 70), point)) { if(once) { NSLog(@"enterred page1"); [self transitionfront:nil]; once = FALSE; } } if (CGRectContainsPoint(CGRectMake(0,0,60,60), point)) { if(once) { NSLog(@"enterred cover"); [self transitionback:nil]; once = FALSE; } } if (CGRectContainsPoint(CGRectMake(100, 15, 30, 30), point)) { if(once){ [self glossary :nil]; once = FALSE; } } return kEventHandled; } -(void)playEffect:(NSString*)sound{ if(effectPlayer!=nil){ [effectPlayer release]; } NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:sound ofType:@"mp3"]]; effectPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [effectPlayer setDelegate:self]; [effectPlayer play]; } -(void)stopEffect { [effectPlayer stop]; } -(void) dealloc{ [super dealloc]; } do pls help me........ do give me a exact coding this is the err..... *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: aesop.mp3)' 2010-05-27 10:43:09.834 abc[276:20b] Stack: ( 11674715, 2476006971, 11758651, 11758490, 5126917, 660698, 660881, 661061, 131577, 448857, 120432, 153433, 630890, 23694899, 23603228, 23630005, 47120081, 11459456, 11455560, 47114125, 47114322, 23633923, 9928, 9814 )

    Read the article

  • How to reduce iOS AVPlayer start delay

    - by Bernt Habermeier
    Note, for the below question: All assets are local on the device -- no network streaming is taking place. The videos contain audio tracks. I'm working on an iOS application that requires playing video files with minimum delay to start the video clip in question. Unfortunately we do not know what specific video clip is next until we actually need to start it up. Specifically: When one video clip is playing, we will know what the next set of (roughly) 10 video clips are, but we don't know which one exactly, until it comes time to 'immediately' play the next clip. What I've done to look at actual start delays is to call addBoundaryTimeObserverForTimes on the video player, with a time period of one millisecond to see when the video actually started to play, and I take the difference of that time stamp with the first place in the code that indicates which asset to start playing. From what I've seen thus-far, I have found that using the combination of AVAsset loading, and then creating an AVPlayerItem from that once it's ready, and then waiting for AVPlayerStatusReadyToPlay before I call play, tends to take between 1 and 3 seconds to start the clip. I've since switched to what I think is roughly equivalent: calling [AVPlayerItem playerItemWithURL:] and waiting for AVPlayerItemStatusReadyToPlay to play. Roughly same performance. One thing I'm observing is that the first AVPlayer item load is slower than the rest. Seems one idea is to pre-flight the AVPlayer with a short / empty asset before trying to play the first video might be of good general practice. [http://stackoverflow.com/questions/900461/slow-start-for-avaudioplayer-the-first-time-a-sound-is-played] I'd love to get the video start times down as much as possible, and have some ideas of things to experiment with, but would like some guidance from anyone that might be able to help. Update: idea 7, below, as-implemented yields switching times of around 500 ms. This is an improvement, but it it'd be nice to get this even faster. Idea 1: Use N AVPlayers (won't work) Using ~ 10 AVPPlayer objects and start-and-pause all ~ 10 clips, and once we know which one we really need, switch to, and un-pause the correct AVPlayer, and start all over again for the next cycle. I don't think this works, because I've read there is roughly a limit of 4 active AVPlayer's in iOS. There was someone asking about this on StackOverflow here, and found out about the 4 AVPlayer limit: fast-switching-between-videos-using-avfoundation Idea 2: Use AVQueuePlayer (won't work) I don't believe that shoving 10 AVPlayerItems into an AVQueuePlayer would pre-load them all for seamless start. AVQueuePlayer is a queue, and I think it really only makes the next video in the queue ready for immediate playback. I don't know which one out of ~10 videos we do want to play back, until it's time to start that one. ios-avplayer-video-preloading Idea 3: Load, Play, and retain AVPlayerItems in background (not 100% sure yet -- but not looking good) I'm looking at if there is any benefit to load and play the first second of each video clip in the background (suppress video and audio output), and keep a reference to each AVPlayerItem, and when we know which item needs to be played for real, swap that one in, and swap the background AVPlayer with the active one. Rinse and Repeat. The theory would be that recently played AVPlayer/AVPlayerItem's may still hold some prepared resources which would make subsequent playback faster. So far, I have not seen benefits from this, but I might not have the AVPlayerLayer setup correctly for the background. I doubt this will really improve things from what I've seen. Idea 4: Use a different file format -- maybe one that is faster to load? I'm currently using .m4v's (video-MPEG4) H.264 format. I have not played around with other formats, but it may well be that some formats are faster to decode / get ready than others. Possible still using video-MPEG4 but with a different codec, or maybe quicktime? Maybe a lossless video format where decoding / setup is faster? Idea 5: Combination of lossless video format + AVQueuePlayer If there is a video format that is fast to load, but maybe where the file size is insane, one idea might be to pre-prepare the first 10 seconds of each video clip with a version that is boated but faster to load, but back that up with an asset that is encoded in H.264. Use an AVQueuePlayer, and add the first 10 seconds in the uncompressed file format, and follow that up with one that is in H.264 which gets up to 10 seconds of prepare/preload time. So I'd get 'the best' of both worlds: fast start times, but also benefits from a more compact format. Idea 6: Use a non-standard AVPlayer / write my own / use someone else's Given my needs, maybe I can't use AVPlayer, but have to resort to AVAssetReader, and decode the first few seconds (possibly write raw file to disk), and when it comes to playback, make use of the raw format to play it back fast. Seems like a huge project to me, and if I go about it in a naive way, it's unclear / unlikely to even work better. Each decoded and uncompressed video frame is 2.25 MB. Naively speaking -- if we go with ~ 30 fps for the video, I'd end up with ~60 MB/s read-from-disk requirement, which is probably impossible / pushing it. Obviously we'd have to do some level of image compression (perhaps native openGL/es compression formats via PVRTC)... but that's kind crazy. Maybe there is a library out there that I can use? Idea 7: Combine everything into a single movie asset, and seekToTime One idea that might be easier than some of the above, is to combine everything into a single movie, and use seekToTime. The thing is that we'd be jumping all around the place. Essentially random access into the movie. I think this may actually work out okay: avplayer-movie-playing-lag-in-ios5 Which approach do you think would be best? So far, I've not made that much progress in terms of reducing the lag.

    Read the article

< Previous Page | 1 2 3 4 5