I need to create an audio player with 4-5 melodies - iphone

I am new in Iphone SDK programming
I need to create audio player but without array. Melodies have names "sound1, sound2, sound3..."
My code here:
NSUInteger x;
for (x=1; x<=tuneNums; x++)
{
path = [[NSBundle mainBundle] pathForResource:#"sound%d" ofType:#"wav"];
if([[NSFileManager defaultManager] fileExistsAtPath:path])
{
aSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
[aSound setNumberOfLoops:0];
aSound.delegate = self;
[aSound prepareToPlay];
}
}
All button I have and work great, but only with one mellody:( But how release 4-5 melodies i dont know :(
P.S. Forgive me for my english I'm just out of Siberia

You are allocating an AVAudioPlayer on each cycle, and you get only one 'melody' because that's the one allocated in the last cycle.
As 7KV7 pointed out, you should allocate one AVAudioPlayer when the user presses a button, play the corresponding audio file, and then release/recreate it when another button is pressed.
Something like:
- (void)button1Pressed:(id)sender {
// release the current player
if(aSound) {
[aSound release], aSound = nil;
}
// create a new player with the first file
aSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
[aSound setNumberOfLoops:0];
aSound.delegate = self;
[aSound prepareToPlay];
}
How to determine which audio file to play when a button is pressed is up to you. If you are going to have only four audio files, the simplest way is to have a fixed number of buttonPressed selectors (e.g. button1Pressed, button2Pressed) and associate them to your four buttons.

if i got you right you should add the method-
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player release];
}
and don't forget to set your view controller as the player delegate.
aSound.delegate=self;

Related

Sound and new images fail to load in View after my app runs for about 30 minutes

I'm working on a game, that at first seem too run fine, but.......
after it runs a long time the sound first stops to work,
[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; returns a null and a little while later when I try to set a view equal to a new image, by view.image=, I get a error in my console that says to many files open,
ImageIO: CGImageRead_mapData 'open' failed '/Users/deno/Library/Application Support/iPhone Simulator/5.1/Applications/5A0C777C-70D1-4AA0-8D7B-04A1F734C932/cPetCakes.app/twinkles04fin32.png'
error = 24 (Too many open files)
right now I creat a new I'm creating a new AVAudioPlayer object each time a sound is played. Should I be re-using the object or some how freeing it??? Since I was not using a alloc, I was thinking that the object would be freed automatcly???
Code for sound
-(void) PlaySound: (NSString *) name
{
NSURL *url;
if ( [name compare:#"chasdog"]==0)
url = [[NSBundle mainBundle]
URLForResource:name
withExtension:#"wav"];
else
url = [[NSBundle mainBundle]
URLForResource:name
withExtension:#"mp3"];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.volume=1.0;
audioPlayer.numberOfLoops= 0;
[audioPlayer play];
audioPlayer.delegate = self;
}
code that no longer loads in new images
self.image=gPetCakeB[gGame->mPetCakeId];
In the player delegate it's needed to release the player once it's stopped playing:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[player release];
}

Playing sound though http server iOS

Hi I want to play a mp3 file via my server e.g. http://test.com/hi.mp3
At the moment the code plays the file if its in the directory of the code.
The code also enables only 1 sound at a time.
- (IBAction)oneSound:(id)sender; {
NSString *path = [[NSBundle mainBundle] pathForResource:#"1" ofType:#"mp3"];
if (theAudio) [theAudio release];
NSError *error = nil;
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
if (error)
NSLog(#"%#",[error localizedDescription]);
theAudio.delegate = self;
[theAudio play];
}
However this code here enables me to play the sound through the http server, but I can play multiple sounds at once, I need the sound in sessions so only 1 sound can play at once. I have 10 sounds.
- (IBAction)oneSound:(id)sender; {
AVPlayer *player = [[AVPlayer playerWithURL:[NSURL URLWithString:#"http://www.mysite.com/hi.mp3"]] retain];
[player play];
}
My suggestion would be to move the pointer for your player from being declared in that method so that it is declared at a module level (in the .h file) - either just defined in the interface, or defined as a #property. Then you can access this player in another method later.
Then when you wish to switch to a new sound in another method you could try:
[player pause]; // stop the player from playing
[player release]; // free the reference count
// start a new plaer
player = [[AVPlayer playerWithURL:
[NSURL URLWithString:#"http://www.mysite.com/nextsound.mp3"]] retain];
You should be careful with the 'retain' call here. The playerWithURL will be passing back an autoreleased object, so depending on what you are doing elsewhere with autorelease pools, and depending on whether you are using a property including (retain) in its definition, you may not need to call retain here.

Whats the simplest way to play a looping sound?

What is the simplest way to play a looping sound in an iPhone app?
Probably the easiest solution would be to use an AVAudioPlayer with the numberOfLoops: set to a negative integer.
// *** In your interface... ***
#import <AVFoundation/AVFoundation.h>
...
AVAudioPlayer *testAudioPlayer;
// *** Implementation... ***
// Load the audio data
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"sample_name" ofType:#"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;
// Set up the audio player
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];
if(audioError != nil) {
NSLog(#"An audio error occurred: \"%#\"", audioError);
}
else {
[testAudioPlayer setNumberOfLoops: -1];
[testAudioPlayer play];
}
// *** In your dealloc... ***
[testAudioPlayer release];
You should also remember to set the appropriate audio category. (See the AVAudioSession setCategory:error: method.)
Finally, you'll need to add the AVFoundation library to your project. To do this, alt click on your project's target in the Groups & Files column in Xcode, and select "Get Info". Then select the General tab, click the + in the bottom "Linked Libraries" pane and select "AVFoundation.framework".
The easiest way would be to use an AVAudioPlayer set to an infinite number of loops (or finite if that's what you need).
Something like:
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourAudioFileName" ofType:#"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *_player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
[file release];
_player.numberOfLoops = -1;
[_player prepareToPlay];
[_player play];
This will simply loop whatever audio file you have specified indefinitely.
Set the number of loops to any positive integer if you have a finite number of times you want the audio file to loop.
Hope this helps.
Cheers.

Audio playing twice upon pressing the home button

HI guys, i am developing a ebook reader. There are some audio files which needs to be played upon clicking on a icon. The audio just plays fine for the first time.. But, when i press the home button of the app and return into the audio player, the audio is being played twice... The number keeps increasing by 1 every time i press the home button and come back to the audio player.... Please help me with ur inputs.... by debugging i found that this loop is running multiple times... Can anyone tell me the reason for it??
-(void)StartPlayingFileWithNotification:(NSNotification *)notifcation{
// Load the array with the sample file
NSString *f = [[notifcation userInfo] valueForKey:#"audiopath"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: f];
if(fileURL == nil){
GLogError(#"%#",#"File Not Found");
return;
}else {
GLogInfo(#"%#",#"Got audio file");
}
if (self.player != nil) {
if (self.player.playing) {
[self.player stop];
}
[player release];
player = nil;
}
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
if (self.player)
{
fileName.text = [NSString stringWithFormat: #"%# (%d ch.)", [[player.url relativePath] lastPathComponent], player.numberOfChannels, nil];
[self updateViewForPlayerInfo:player];
player.numberOfLoops = 0;
player.delegate = self;
[player play];
[self updateViewForPlayerState:player];
}
[fileURL release];
}
Sounds like you are creating new views (or other objects) containing your audio player without checking to see if the previous one is still around and running. You could either check on activate before creating another one, or clean up the old one when the app resigns active.

How do I keep music playing after the user presses the hold button on the iPhone?

Hey guys how can I make an app keep playing an mp3 after pressed the hold/power button.
Here is the code I use for preparing the AVAudioPlayer:
- (void)PrepareAudio:(int)index
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#",[_Audio objectAtIndex:Game]] ofType:#"mp3"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
MusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: newURL error: nil];
[newURL release];
[MusicPlayer setVolume: 1.5];
}
And this is the code when I press the button play:
- (IBAction)PushPlay: (id)sender
{
if(!MusicPlayer.playing)
[MusicPlayer play];
}
Best Regards
Carlos Vargas
If you are holding long enough to turn the device off, then there is no way. If you are pressing the button to lock the screen, the music can be played. Why don't you put some code up and let us see what you have tried. Hint: The answer lies within the Audio playback categories.