I am very new to programming and I am just working on my first app. I haven't been able to find an answer to this for weeks. I would really appreciate some help.
I have background music through AVAudioPlayer (the only sound in my app) that begins playing when my app opens - here is the code in my appdelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *bgmusic=[[NSBundle mainBundle]pathForResource:#"cloud_two-full-" ofType:#"mp3"];
bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
bgmusic1.delegate=self;
bgmusic1.numberOfLoops=-1;
[bgmusic1 play];
[bgmusic1 setVolume:1.0];
}
So, I've created a uiswitch that I want to use to be able to mute the background music. Here is the IBAction in my viewcontroller.m:
- (IBAction)speakerOnOff:(id)sender {
static BOOL muted = NO;
if (muted) {
[bgmusic1 setVolume:1.0];
} else {
[bgmusic1 setVolume:0.0];
}
muted = !muted;
}
But when I click the switch to off the music continues to play at its normal volume. I only have 1 view controller. Please help! I just want the music to mute when the switch is clicked to off and then back to volume 1.0 when the switch is back on.
Write this code
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
above
bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
and make your button action like this
- (IBAction)speakerOnOff:(id)sender {
if ( bgmusic1.volume == 0) {
bgmusic1.volume = 1;
} else {
bgmusic1.volume =0;
}
}
Related
My app uses Audio Queue Services to play sounds. On app start, I set audio session category to solo ambient:
`[[AVAudioSession sharedInstance] setCategory:AVAudioSEssionCategorySoloAmbient error:&error];`
When my app delegate gets applicationWillResignActive notification, I call AudioQueuePause(queue); for all playing sounds. And when the app delegate gets applicationDidBecomeActive, I call
OSStatus status = AudioQueueStart(queue, 0);
Sometimes (and it's hard to reproduce) status equals to 561015905. This value does not belong to Audio Queue Result Codes. It is AVAudioSessionErrorCodeCannotStartPlaying, and docs say
"The app is not allowed to start recording and/or playing, usually because of a lack of audio key in its Info.plist. This could also
happen if the app has this key but uses a category that can't record
and/or play in the background (AVAudioSessionCategoryAmbient,
AVAudioSessionCategorySoloAmbient, etc.)."
I definitely do not want to play the sound in background (that's why I am pausing audio queues when app resigns active). So, what am I doing wrong?
I had a similar problem, but I made a little in a different way...There was musical app in which background music was necessary, but under certain conditions she has to howled to play in background mode.
For me, i use this code:
#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVAudioPlayer.h>
#import <AVFoundation/AVAudioSession.h>
#interface ViewController ()
{
AVAudioPlayer *audioPlayer;
}
#property (assign) SystemSoundID pewPewSound;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL * pewPewURL = [[NSBundle mainBundle]URLForResource:#"Calypso" withExtension:#"caf"];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:pewPewURL error:nil];
if (audioPlayer)
{
[audioPlayer setNumberOfLoops:100];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
}
#end
If u don't touch any Xcode setting, this code play looping melody, only in foreground, and if u go to background, player is stopped.
if u do this:
melody will continue to play in background, and in my case i can stop and play melody in background and foreground when i want. And I add system sound to call then u stop player, system sound stopped then U continue play music.
-(void)stopPlaying
{
[audioPlayer pause];
NSURL * pewPewURL;
pewPewURL = [[NSBundle mainBundle]URLForResource:#"Calypso" withExtension:#"caf"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pewPewURL, &_pewPewSound);
AudioServicesPlaySystemSound(self.pewPewSound);
}
-(void)continueToPlay
{
if ([audioPlayer prepareToPlay])
{
[audioPlayer play];
AudioServicesRemoveSystemSoundCompletion(self.pewPewSound);
AudioServicesDisposeSystemSoundID(self.pewPewSound);
}
}
I hope it will help to solve yours problems, If there are questions, set I will answer everything.
In my application, I have one audio file. I want pause or stop the audio by clicking the button. I have tried with some code, but it still plays the audio. Please tell how to pause the audio or stop it by clicking the button.
Stop code.
- (IBAction)back:(id)sender {
[self.audioPlayer isPlaying];
[self.audioPlayer stop];
}
I have used the above to stop the playing audio but its not working.
where am I doing wrong? How to stop the audio?
Stopping Audio is easy just you need to take 2 Action Method for 2 separate buttons 1->Play and 2->Stop then code is as fallows
-(IBAction)Play:(id)sender
{
[self.audioPlayer play];
}
-(IBAction)Stop:(id)sender
{
[self.audioPlayer stop];
}
Another way is to use BOOL and use the 1 Action method to play and stop like this
First declare BOOl object
BOOL AudioBool;
-(IBAction)Audio:(id)sender
{
if(AudioBool == YES)
{
[self.audioPlayer play];
AudioBool = NO;
}
else
{
[self.audioPlayer stop];
AudioBool = YES;
}
}
I am starting to get convinced that iOS is just pure magic. I looked through numerous posts on AVAudioPlayer for solutions, but none worked.
When the application starts I have a movie starting off from MPMoviePlayerController and I have AVAudioPlayer kicking off with a sound as follows:
-(void)createAndPlayMovieFromURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType{
/* Create a new movie player object. */
player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
player.controlStyle = MPMovieControlModeDefault;
if (player)
{
/* Save the movie object. */
[self setMoviePlayerController:player];
/* Specify the URL that points to the movie file. */
[player setContentURL:movieURL];
/* If you specify the movie type before playing the movie it can result
in faster load times. */
[player setMovieSourceType:sourceType];
CGRect frame = CGRectMake(0, 0, 480, 320);
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:frame];
[player view].backgroundColor = [UIColor blackColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[self.view addSubview: [player view]];
}
[[self moviePlayerController] play];
}
and for sound:
- (void)setupAudioPlayBack:(NSString *) path : (NSString *) extension{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:path
ofType:extension]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
}
And now lets talk magic. When the first movie plays and the sound, the sound is not responding to either the volume controls on the phone nor to Silent Mode On switch.
But then immediately a second movie plays with its own sound and everything works fine - there is no sound with Silent Mode On, if Silent Mode Off it responds to Volume Controls. 3rd movie - plays perfectly too.
I tried using the player.useApplicationAudioSession = NO for MPMoviePlayerController - fixed the problem with the first time sound not responding to Silent Mode or Volume Controls, but now when the second movie starts to play it freezes instantly and the sound played is cut from the original size to something around 2 seconds.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil]; didn't help either wherever I set it.
So my question is - how to make the MPMoviePlayerController interact with AVAudioPlayer without any problems...
Ok I actually found a solution (once again, magic).
When you start your ViewController you set it up as follows:
- (void)viewDidLoad
{
[self setupAudioPlayBack:#"sound1" :#"caf"];
[self playMovieFile:[self localMovieURL:#"mov1" :#"mov"]];
audioTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(playAudio) userInfo:nil repeats:NO];
[super viewDidLoad];
}
Where the playAudio method is simply:
- (void)playAudio{
[audioPlayer play];
}
Just 0.1 millisecond timer is enough to make everything work (0.0 doesn't work) and make sure a new video doesn't start before the audio finishes or it will destroy the settings so you will have to invalidate the timer and redo the timer again.
I have an iPhone app (5.1 SDK) which plays audio in the background. Many times when there is an incoming call, the incoming call is displayed but the user cannot slide the slider to answer it and the call is missed.
I am using - (void)beginInterruption to pause all audio when an incoming call arrives but it doesn't seem to stop this issue from occurring.
Has anyone ever encountered this before?
In case you wanna mark this as the answer since it was indeed your problem I'll repost my comment.
Is your beginInterruption code being called? If so, is the music actually stopping? Are you streaming audio over the network or local files? What player are you using?
- (void) beginInterruption {
if (playing) {
playing = NO;
interruptedWhilePlaying = YES;
[self updateUserInterface];
}
}
NSError *activationError = nil;
- (void) endInterruption {
if (interruptedWhilePlaying) {
BOOL success = [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
if (!success) { /* handle the error in activationError */ }
[player play];
playing = YES;
interruptedWhilePlaying = NO;
[self updateUserInterface];
}
}
I am using AVPlayer to play a live stream from the Internet using the following code :
NSString *u = #"http://192.192.192.192:8036";
NSURL *url = [NSURL URLWithString:u];
radiosound = [[AVPlayer alloc] initWithURL:url];
[radiosound play];
And I have one button play :
[radiosound play];
and Pause :
[radiosound pause];
My issue is that I want to use only one button Play/Pause, but when I am using this code
if (radiosound.isPlaying) {
[radiosound pause];
} else {
[radiosound play];
}
My app crashes, because AVPlayer doesn´t recognize "isPlaying".
Any tips?
AVPlayer doesn't have an isPlaying property. Use the rate property (0.0 means stopped, 1.0 playing).
if (radiosound.rate == 1.0) {
[radiosound pause];
} else {
[radiosound play];
}
You can look at the AVPlayer class reference here.
After some research I found out that when there is no network connection, AVPlayer still sets the rate to 1.0 after receiving a -play message.
Thus, I also check for the currentItem and modified my method like that:
-(BOOL)isPlaying
{
if (self.player.currentItem && self.player.rate != 0)
{
return YES;
}
return NO;
}
Please share your opinion if you think something is wrong with this approach.