How to stop play sound if silent mode is turned on - iphone

My code:
NSString *soundName = [[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"];
NSURL *soundURL = [NSURL fileURLWithPath:soundName];
NSError *error = [[NSError alloc] init];
self.backgroundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
if (self.backgroundPlayer == nil) {
NSLog(#"error = %#",[error description]);
} else {
[self.backgroundPlayer setDelegate:self];
[self.backgroundPlayer setNumberOfLoops:HUGE_VAL];
[self.backgroundPlayer setVolume:0.5f];
[self.backgroundPlayer prepareToPlay];
if ([self.backgroundPlayer prepareToPlay]) {
if ([self.backgroundPlayer play]) {
NSLog(#"playing");
}
} else {
NSLog(#"error!");
}
}
When I switch iPhone to silent mode sound still plays. How can I solve this problem?

I haven't tried this, but you can set the audio category before playing the file:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];

CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if(CFStringGetLength(state) == 0)
{
//SI
else
{
//NOT SILENT
}
you can detect the state of phone and stop your player .. :)

You need to user AVAudioSessionCategoryAmbient for audio session. go though audio session programming guide.

Related

AVAudioPlayer volume is low (How to set volume from speaker)

I use AVAudioPlayer for playing sounds but when playing, the sound volume is very low.
I done a search and found many codes about adding session property or session category but I'm wondering how to use it.
-(void) playVoice: (NSString *) path
{
if([path isEqualToString:#""] == NO)
{
//Initialize the AVAudioPlayer.
NSData *soundData= [NSData dataWithContentsOfFile:path];
NSError *error;
audioPlayer= [[AVAudioPlayer alloc] initWithData:soundData error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
NSLog(#"total time=%f", self.audioPlayer.currentTime);
self.PlayStatusSlider.maximumValue= audioPlayer.duration;
myTimer= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(changeAudioProgress) userInfo:nil repeats:YES];
[audioPlayer prepareToPlay];
[audioPlayer setVolume:1.0];
[audioPlayer play];
}
}else{
// NSLog(#"ErrorDownloading");
}
}
- (void) configureAVAudioSession
{
//get your app's audioSession singleton object
AVAudioSession* session = [AVAudioSession sharedInstance];
//error handling
BOOL success;
NSError* error;
//set the audioSession category.
//Needs to be Record or PlayAndRecord to use audioRouteOverride:
success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
error:&error];
if (!success) NSLog(#"AVAudioSession error setting category:%#",error);
//set the audioSession override
success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
error:&error];
if (!success) NSLog(#"AVAudioSession error overrideOutputAudioPort:%#",error);
//activate the audio session
success = [session setActive:YES error:&error];
if (!success) NSLog(#"AVAudioSession error activating: %#",error);
else NSLog(#"audioSession active");
}
but it is not working for me. Witch part is wrong? How should I use it?
You have to set your audio session to default to speaker.
To anyone coming across this question now:
private var configureAudioSessionError: NSError?
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
try audioSession.setActive(true)
} catch let error as NSError {
configureAudioSessionError = error
}

Can AVFoundation play Audio and get Details of it On the IOS 5.0 Simulator?

Can the Above be Done using only AVFoundation.framework?
i Tried doing a few experiment but i can't really get it to work
(sorry newbie here please do tell me where to put the codes at Example: ViewController or the MainView)
These are my code,(UI Components are inside as i'm do not want use interface builder)
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSError *error;
buttonPlay = [[UILabel alloc] initWithFrame:CGRectMake(0, 350, 100, 50)];
buttonPlay.text = #"Play";
// Get the file path to the song to play.
NSString* path;
NSURL* url;
path = [[NSBundle mainBundle] pathForResource:#"Bring_Me_To_Life.mp3" ofType:nil];
url = [NSURL fileURLWithPath:path];
NSData *_objectData = [NSData dataWithContentsOfURL:url];
//Initialize the AVAudioPlayer.
audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
// Preloads the buffer and prepares the audio for playing.
audioPlayer.numberOfLoops = 0;
audioPlayer.volume = 1.0f;
[audioPlayer prepareToPlay];
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
[self addSubview:buttonPlay];
}
return self;
}
-(void)touchesBegan:(CGPoint)location{
if(CGRectContainsPoint(buttonPlay.frame, location)){
NSLog(#"Dec from Chl %f",[audioPlayer peakPowerForChannel:0]);
NSLog(#"Length of Clip %f",[audioPlayer duration]);
}
}
try this
audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

AVPlayer not playing from music library

I am trying to play a song from my iPhone music library using AVPlayer. Everything seems ready to play, but the player simply won't make any sound. I've been struggling with this for a while, any help would be greatly appreciated!
Note: I realize I could use AVAudioPlayer, but I would like to read the file right from my music library and, to my understanding, AVAudioPlayer doesn't support that (I would have to export the song first, taking up more time). I cannot use MPMusicPlayerController because the end goal is to turn the song into NSData and play it on another device.
Above all, I would like to know WHY this code isn't playing:
NSArray *itemsFromQuery = [[MPMediaQuery songsQuery] items];
MPMediaItem *song = [itemsFromQuery objectAtIndex:29];
NSURL *songURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:songURL options:nil];
NSArray *keyArray = [[NSArray alloc] initWithObjects:#"tracks", nil];
[urlAsset loadValuesAsynchronouslyForKeys:keyArray completionHandler:^{
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:urlAsset];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
while (true) {
if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay) {
break;
}
}
if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay) {
NSLog(#"Ready to play");
[player play];
}
else
NSLog(#"Not ready to play");
}];
The output is "Ready to play", and the "rate" property of the AVPlayer is 1.0 after I call the play method. The MPMediaItem exists, and I can use the valueForProperty method to obtain the correct title, artist, etc. Any ideas why no sound is coming from the player?
Found something that worked:
I made the AVPlayer a property (thanks for the tip meggar!)
I made sure the AVPlayer was nil before using the initWithAsset method.
NSArray *itemsFromQuery = [[MPMediaQuery songsQuery] items];
MPMediaItem *song = [itemsFromQuery objectAtIndex:0];
NSURL *songURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:songURL options:nil];
NSArray *keyArray = [[NSArray alloc] initWithObjects:#"tracks", nil];
[urlAsset loadValuesAsynchronouslyForKeys:keyArray completionHandler:^{
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:urlAsset];
player = nil;
player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
while (true) {
if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay)
break;
}
[player play];
}];
Hope this helps someone out!
Another reason is configuring AVAudioSession. Worked for me.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

can I stop the play back using my app

I am using AudioPlayer to stop all playbacks , as code is given
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
But i can stop all play back using this but can not again play stopped play backs.How can I do this please help
You can easily play pause stop your AVAudioPlayer with these three methods:
- (void)pause
- (void)stop
- (BOOL)play //Returns YES on success, or NO on error.
If you pause, you can then play to resume from where you paused.
Hope this helps, i really don't see where your problem is!
in the code you gave, you are not pausing, you are just playing it with numberOfLoops negative.
You should have a method to start your music like this:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;//play once
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer prepareToPlay];
[audioPlayer play];
And another for pausing:
[audioPlayer pause];
And another for resuming:
[audioPlayer play];
To toggle iPod music when the app starts and exits override these two methods:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
MPMusicPlayerController *musicPlayer;
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if (playbackState == MPMusicPlaybackStatePlaying) { //simple verification
[musicPlayer pause];
}
}
- (void)applicationWillResignActive:(UIApplication *)application
if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {//simple verification
[musicPlayer play];
}
}
Hope it finally suits your needs!

stopping an AVAudioPlayer

here is my code
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"95" ofType:#"wav"];
NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];
NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
musicPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];
if (musicPlayer1) {
[musicPlayer1 stop];
[musicPlayer1 release];
musicPlayer1 = nil;
}
else {
[musicPlayer1 prepareToPlay];
[musicPlayer1 setVolume:.8];
[musicPlayer1 setNumberOfLoops:-1]; // -1 means play indefintely
[musicPlayer1 setDelegate: self];
[musicPlayer1 play];
}
}
I am rying to start and stop the AVAudioPlay with the same button (musicPlayer1 is in the header). Now when i touch the button it does not play anything. Help please?
You're creating a new instance of AVAudioPlayer each time. You need to hold onto the reference to the object somewhere, and refer back to that. Add a field to your view controller class:
#private AVAudioPlayer *currentAudio;
And then in this method, make the following changes:
if (currentAudio) {
[currentAudio stop];
[currentAudio release];
currentAudio = nil;
} else {
// what you already have goes here
}