Problem regarding overlapping song? - iphone

I am using a AVAudio player to play a song,
I take a song from ipod library,
i play a first song but when select other song from ipod library that both song play simultaneously,
How to stop a first song?
I tried to stop a song
- (IBAction)player_stop {
[theAudio stop];
theAudio = Nil;
}
on button play method i write this code
- (IBAction)btn_play {
[self player_stop];
[theAudio play];
}
How i Do that?

You should tell the player, not the audio, to stop.
[self.player stop];
To start a new audio you can do as follows:
[self.player stop];
self.player = nil;
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[self.player play];

Related

AVAudioPlayer behaviour handling issue

I have been trying to learn AVAudioPlayer and it's behaviour.
So to start with I had written
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1;
[player play];
It did worked well as long as application did not enter background. So I searched again and found that I need to add entry in plist and also have written following code
NSError *activationError = nil;
if([[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&activationError] == NO)
NSLog(#"*** %# ***", activationError);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Now my sample application plays sound in background as well. Then I encountered another problem. If I put sleep before all this processing, take my application in background during the sleep and start playing music from some other app, in this case my application is not able to play sound. It is probably because it does not get the audio session which some other music application has taken.
Questions
1. I understand that there is a way to detect if any other sound is playing, but I could not find how do I stop it. There are methods for stopping standard app sound like iPod, but is there any generic method to stop the sound from any other application.
2. [player play]; gives NO as result which is failure. How do I find what failure has caused. I have implemented audioPlayerDecodeErrorDidOccur:error: method, but it is never called.
Please share your knowledge on this. I have already gone through most of the stack overflow questions regarding the same, but did not find anything useful to this particular problem.
-(void)loadPlayer
{
NSURL *audioFileLocationURL = [NSURL URLWithString:[[NSBundle mainBundle] URLForResource:#"01-YedhiYedhi[www.AtoZmp3.in]" withExtension:#"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[audioPlayer setNumberOfLoops:-1];
if (error)
{
NSLog(#"%#", [error localizedDescription]);
[[self volumeControl] setEnabled:NO];
[[self playPauseButton] setEnabled:NO];
[[self alertLabel] setText:#"Unable to load file"];
[[self alertLabel] setHidden:NO];
}
else
{
[[self alertLabel] setText:[NSString stringWithFormat:#"%# has loaded", str]];
[[self alertLabel] setHidden:NO];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
//Load the audio into memory
[audioPlayer prepareToPlay];
}
}
if (!self.audioPlayer.playing) {
[self playAudio];
} else if (self.audioPlayer.playing) {
[self pauseAudio];
}
}
- (void)playAudio {
[audioPlayer play];
}

Play silent videos alongwith the Music App playing songs

Ok, so I have an app in which there are many videos of exercises, which do not have any sound at all.
Also, at the start of the exercises, I display all the mp3 files from the Music Player of the device for the User to select audio files.
But, then whenever the video starts, the Music Player gets paused. How do I make it work in such a way that Music Player keeps on playing and Video also plays simultaneously.
For Video, using the class -- MPMoviePlayerViewController
It is added as follows :
self.movieplayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:urlStr];
self.movieplayerController.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
self.movieplayerController.moviePlayer.fullscreen = YES;
self.movieplayerController.moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(movieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self presentModalViewController:movieplayerController animated:YES];
For Music Player, class is --- MPMusicPlayerController.
Audio is selected and played as follows :
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissModalViewControllerAnimated: YES];
[self.musicPlayer stop];
[self.musicPlayer setQueueWithItemCollection:mediaItemCollection];
[self.musicPlayer play];
}
EDIT :
Also, tried the AVPlayer for playing videos but no success!
Code is as follows :
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:urlStr];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
avPlayerLayer.frame = self.view.frame;
[self.view.layer addSublayer:avPlayerLayer];
[player play];
Got the answer finally....
Works with AVPlayer.
Initialize it as above in the question.
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:urlStr];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
avPlayerLayer.frame = self.view.frame;
[self.view.layer addSublayer:avPlayerLayer];
[player play];
But before this, in the AppDelegate, create a AudioSession which would allow the Mixing.
AudioSessionInitialize(NULL, NULL, NULL, NULL);
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
UInt32 allowMixWithOthers = true;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(allowMixWithOthers), &allowMixWithOthers);
AudioSessionSetActive(true);
Got the answer from here.
App with AVPlayer plays mp4 interrupt iPod music after launched
You can use AudioToolbox for this purpose. I've developed a small demo (after reading your question) and its working.
Download the demo for MPMoviePlayerViewController from here : - http://mobile.tutsplus.com/tutorials/iphone/mediaplayer-framework_mpmovieplayercontroller_ios4/
Now add the any .wav file to your bundle.
Now modify this method :
-(IBAction)playMovie:(id)sender
{
UIButton *playButton = (UIButton *) sender;
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"big-buck-bunny-clip" ofType:#"m4v"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
MPMoviePlayerViewController *moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:fileURL];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackComplete:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
[moviePlayerController.view setFrame:CGRectMake(playButton.frame.origin.x,
playButton.frame.origin.y,
playButton.frame.size.width,
playButton.frame.size.height)];
[self.view addSubview:moviePlayerController.view];
//moviePlayerController.fullscreen = YES;
//moviePlayerController.scalingMode = MPMovieScalingModeFill;
[moviePlayerController.moviePlayer play];
NSString *soundPath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
AudioServicesPlaySystemSound (soundID);
[soundPath release];
}
It just a demo. Hope it helps further...
Unfortunately, AudioSessionInitialize and friends were deprecated with iOS7. Its much easier to mix now with AVAudioSession. I use the audioSession object as a global - not sure what would happen if it was deallocated. AVPlayer sure gives up in a hurry if it's declared on the stack - so beware of that gotcha.
_audioSession = [AVAudioSession sharedInstance];
[_audioSession setCategory:AVAudioSessionCategoryAmbient error:&theError];

AVAudioPlayer - Pause button

My previous code was
- (void) playaudio: (id) sender
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Theme"
ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
self.audioPlayer.currentTime = 0;
[self.audioPlayer play];
}
- (void)pause: (id)sender
{
[audioPlayer pause];
}
- (void)stop: (id)sender
{
[audioPlayer stop];
}
In the above code pause button was acting as stop button rather than pause where it was supposed to resume the audio file.
Now i have added simple statements to my code it is working to some extent but still not upto my expectations.
What happening now is when you play audio file and click on pause button nothing happens but when you click on the stop button it stops playing audio file and then when you press the pause button it resumes the audio file from where it was stopped by pressing stop button. Why is that when you press stop buttons only then pause button functions but not before that. I don't get this why?
Any ideas why this is happening
- (void)pause: (id)sender
{
[audioPlayer pause];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
- (void) stop: (id) sender
{
[audioPlayer stop];
}
If anyone have any ideas that why this is happening. Will appreciate help.
Thanks in advance.
You shouldn't be recreating the audio file every time you play it. Here is how you could do this:
- (void) playaudio: (id) sender
{
if(self.audioPlayer == nil) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Theme"
ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
self.audioPlayer.currentTime = 0; //this could be outside the if if you want it to start over when they hit play
}
[self.audioPlayer play];
}
- (void)pause: (id)sender
{
if([audioPlayer isPlaying]){
[audioPlayer pause];
} else {
[audioPlayer play];
}
}
- (void)stop: (id)sender
{
[audioPlayer stop];
}

Iphone application with audio player

I have added music files in application's document folder and I am playing that music from AVAudioPlayer. How can I get Its title , album name and artist name.
I used MPmediaPlayer to access ipod library . but now I want to make my custom player. Is there any need to use mpmediaplayer in this type of app.I already get the albumtitle and artwork image of ipod songs
I am trying to get it like
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
// Instantiates the AVAudioPlayer object, initializing it with the sound AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil]; self.appSoundPlayer
= newPlayer;
musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
MPMediaItem *item = musicPlayer.nowPlayingItem ;
nowPlayingLabel.text = [item valueForProperty:MPMediaItemPropertyTitle];
NSLog(#"title %#",[item valueForProperty:MPMediaItemPropertyTitle]); [newPlayer release]; // "Preparing to play" attaches to the audio hardware and ensures that playback // starts quickly when the user taps Play [appSoundPlayer prepareToPlay]; [appSoundPlayer setVolume: 1.0]; [appSoundPlayer setDelegate: self];
[appSoundPlayer currentTime];
title is returning (null)
Please help..

Iphone : while play one song another song overlap.

In my app song play from ipod library through AVAudioPlayer,
problem is that when one song is play & select second song,
second song overlap,
i try to stop the song with call this method
- (IBAction)player_stop {
theAudio.delegate = nil;
[theAudio release];
theAudio = nil;
}
I try this method but not going in this condition
if (theAudio.isPlaying == YES){
[theAudio release];
theAudio = nil;
}
theAudio is Object of AVAudioplayer,
How can i do that?
what about
if (theAudio.isPlaying == YES){
[theAudio stop];
}