Avoid audio to continue in another view - ios

I have an app where I play an audio-file on launch in the View Controller. I also have a button that switches to my second view. My problem is that the audio continues to play even after I have switched view. Here's my code for ViewController.m:
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
#end
#implementation ViewController
//When I go to this view, I want the audio to stop
- (IBAction)SwitchView:(id)sender {
SecondViewController *second = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:NULL];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"home_sound"
ofType:#"mp3"]];
NSError *error;
homeaudioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
homeaudioPlayer.delegate = self;
[homeaudioPlayer setNumberOfLoops: -1];
[homeaudioPlayer prepareToPlay];
}
[homeaudioPlayer play];
}
#end
How can I do this?
Thanks.

update your SwitchView code-
- (IBAction)SwitchView:(id)sender {
[homeaudioPlayer stop];
SecondViewController *second = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:NULL];
}

Simply add [homeaudioPlayer stop]; to your switchView method. This should stop all sound that the player is playing.

Related

AVAudioPlayer is always nill and its isPlaying property is always false. The files are mixed while playing

I've been pulling out my hair past three days to fix this problem. I've checked lots of sample codes, read lots of tutorials, and googled and checked lots and lots of questions and answers on stackoverflow, but I still cannot fix the problem. There are several similar questions like this or this but they don't have any solutions either.
So a little bit about my project:
I have a NIKMasterViewController and a NIKDetailViewController. In the first one I have a list of audio files in a table view; selecting a row, it navigates to the NIKDetailViewController where the user can see some info about the file and play the audio file.
I've defined an AVAudioPlayer property in the NIKMasterViewController and have set it like this:
NIKMasterViewController.h:
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
NIKMasterViewController.m:
#synthesize audioPlayer;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"])
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
NIKDetailViewController *detailViewController = (NIKDetailViewController *) segue.destinationViewController;
[detailViewController setAudioPlayer:audioPlayer];
[detailViewController setFeedEntry:[[[self feedParser] feedItems] objectAtIndex:indexPath.row]];
} else {
NSLog(#"Segue Identifier: %#", segue.identifier);
}
}
And that's all about the AVAudioPlayer in NIKMasterViewController. Now in my NIKDetailViewController I have another property of AVAudioPlayer:
NIKDetailViewController.h:
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
Now in my .m file I have a method called streamAudio which is called in viewDidLoad to prepare the audio playback, and I have an if condition asking to check if the audioPlayer is nill and if not, if the audioPlayer.isPlaying is true so that it stops the player, but it's never called, and when i navigate back to the Master VC to tap on another row to play another file, the second file starts playing while the first file is being played and everything gets mixed up.
Any help will be truly appreciated, since I'm almost about to stop programming after being unable to fix this issue after hours and days!
NIKDetailViewController.m:
#synthesize audioPlayer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
selectedItem = [[NSString alloc]init];
}
return self;
}
#pragma mark - Managing the Audio Playback
- (IBAction)togglePlayingState:(id)button
{
//Handle the button pressing
[self togglePlayPause];
}
- (void)playAudio
{
//Play the audio and set the button to represent the audio is playing
[audioPlayer play];
[playPauseButton setImage:[UIImage imageNamed:#"player_pause"] forState:UIControlStateNormal];
}
- (void)pauseAudio
{
//Pause the audio and set the button to represent the audio is paused
[audioPlayer pause];
[playPauseButton setImage:[UIImage imageNamed:#"player_play"] forState:UIControlStateNormal];
}
- (void)togglePlayPause
{
//Toggle if the music is playing or paused
if (!audioPlayer.playing)
{
[self playAudio];
}
else if (audioPlayer.playing)
{
[self pauseAudio];
}
}
- (void)streamAudio
{
currentFileName = [[feedEntry podcastDownloadURL] lastPathComponent];
NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* path = [documentPath stringByAppendingPathComponent:currentFileName];
NSURL* audioURL = [NSURL fileURLWithPath: path];
if (audioPlayer != nil)
{
if (audioPlayer.isPlaying)
{
[audioPlayer stop]; //THIS IS NEVER CALLED
}
audioPlayer = nil; //THIS IS NEVER CALLED
}
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
// Set a timer which keep getting the current music time and update the UISlider in 1 sec interval
playbackTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateSlider) userInfo:nil repeats:YES];
// Set the maximum value of the UISlider
seekSlider.maximumValue = audioPlayer.duration;
currentTime.text = [NSString stringWithFormat:#"%d:%02d", (int)audioPlayer.currentTime / 60, (int)audioPlayer.currentTime % 60, nil];
remainingTime.text = [NSString stringWithFormat:#"%d:%02d", (int)(audioPlayer.duration - audioPlayer.currentTime) / 60, (int)(audioPlayer.duration - audioPlayer.currentTime) % 60, nil];
// Set the valueChanged target
[seekSlider addTarget:self action:#selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
audioPlayer.delegate = self;
[audioPlayer prepareToPlay]; //Add the audio to the memory.
}
- (void)updateSlider
{
// Update the slider about the music time
seekSlider.value = audioPlayer.currentTime;
}
- (IBAction)sliderChanged:(UISlider *)sender {
// Fast skip the music when user scrolls the slider
[audioPlayer stop];
[audioPlayer setCurrentTime:seekSlider.value];
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer play];
}
// Stop the timer when the music is finished (Need to implement the AVAudioPlayerDelegate in the Controller header)
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
// Music completed
if (flag) {
[playbackTimer invalidate];
}
}
- (IBAction)forwardAudio:(id)sender
{
int currentTime = [audioPlayer currentTime];
[audioPlayer setCurrentTime:currentTime+10];
}
- (IBAction)rewindAudio:(id)sender
{
int currentTime = [audioPlayer currentTime];
[audioPlayer setCurrentTime:currentTime-10];
}
//Make sure we can recieve remote control events
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
//if it is a remote control event handle it correctly
if (event.type == UIEventTypeRemoteControl) {
if (event.subtype == UIEventSubtypeRemoteControlPlay) {
[self playAudio];
} else if (event.subtype == UIEventSubtypeRemoteControlPause) {
[self pauseAudio];
} else if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {
[self togglePlayPause];
}
}
}
#pragma mark - view life cycle
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
//Once the view has loaded then we can register to begin recieving controls and we can become the first responder
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//End recieving events
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self streamAudio];
//Make sure the system follows our playback status - to support the playback when the app enters the background mode.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
NOTE: I have tried setting the property in the Detail VC as weak but then, I get a warning, and the property is release before I can play the file.
So... I could finally fix this problem by creating a singleton of the audioplayer. This is how:
First of all, I removed all the code related to the audioPlayer from my NIKMasterViewController class, that includes the audioPlayer declaration and setting it in prepareForSegue.
I created a new class called NIKAudioPlayer.
In NIKAudioPlayer.h:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#interface NIKAudioPlayer : NSObject <AVAudioPlayerDelegate>
{
AVAudioPlayer *currentPlayer;
}
#property (nonatomic, strong) AVAudioPlayer *currentPlayer;
+(NIKAudioPlayer *) sharedPlayer;
-(void)playURL:(NSURL*)url;
#end
In NIKAudioPlayer.m:
#import "NIKAudioPlayer.h"
#implementation NIKAudioPlayer
#synthesize currentPlayer;
+(NIKAudioPlayer *) sharedPlayer
{
static NIKAudioPlayer* sharedPlayer;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedPlayer = [[NIKAudioPlayer alloc] init];
});
return sharedPlayer;
}
-(void)playURL:(NSURL*)url
{
[currentPlayer stop];
currentPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[currentPlayer prepareToPlay];
}
#end
Now in everywhere else in the code (in my case in NIKDetailViewController) whenever I need to play an audio file, I call the sharedPlayer from NIKAudioPlayer:
[[NIKPlayer sharedPlayer] playURL:audioURL];
[[NIKPlayer sharedPlayer].currentPlayer prepareToPlay];
To put in a nutshell, replace all audioPlayers in NIKDetailViewController with [NIKPlayer sharedPlayer].currentPlayer, or even cast it and use it everywhere:
audioPlayer = [NIKPlayer sharedPlayer].currentPlayer

Send Audio by Email

How could I get the audio from phone and get it to share via email?
Will it available?
Can we share it simply like music at application?
Your question could have been better, you should show what you've tried, your specific problem, your actual results and your expected result.
Having said that, this sounded like a nice challenge.. so the answer follows.
I'm not sure if you wanted to get the music from the iPod or the app bundle so I implemented the iPod version as (in my opinion), it's more complex.
SSCCE:
main.m
#import "AppDelegate.h"
int main(int argc, char * argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
AppDelegate.h
#import UIKit;
#import MessageUI;
#import MediaPlayer;
#interface AppDelegate : UIResponder <UIApplicationDelegate, MFMailComposeViewControllerDelegate, MPMediaPickerControllerDelegate>
#property (strong, nonatomic) UIWindow *window;
#end
AppDelegate.m
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
UIViewController *controller = [[UIViewController alloc] init];
_window.rootViewController = controller;
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAny];
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = YES;
mediaPicker.prompt = #"Select songs to play";
[_window.rootViewController presentViewController:mediaPicker animated:YES completion:^{
}];
return YES;
}
-(void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
NSLog(#"Result:%d", result);
[controller dismissViewControllerAnimated:YES completion:nil];
}
-(void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[mediaPicker dismissViewControllerAnimated:YES completion:^{
NSArray *recipents = #[#"a#b.com"];
MFMailComposeViewController *messageController = [[MFMailComposeViewController alloc] init];
messageController.mailComposeDelegate = self;
[messageController setToRecipients:recipents];
[messageController setMessageBody:#"Here is a music track" isHTML:NO];
[messageController setSubject:#"Music"];
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
for (MPMediaItem *item in mediaItemCollection.items)
{
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
AVAsset *asset = [AVAsset assetWithURL:url];
NSArray *presets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];
AVAssetExportSession *session = [AVAssetExportSession exportSessionWithAsset:asset presetName:presets[0]];
session.outputURL = [[tmpDirURL URLByAppendingPathComponent:#"item"] URLByAppendingPathExtension:#"m4a"];
session.outputFileType = [session supportedFileTypes][0];
[session exportAsynchronouslyWithCompletionHandler:^{
NSData *data = [NSData dataWithContentsOfURL:session.outputURL];
[messageController addAttachmentData:data mimeType:#"audio/mp4" fileName:#"musicAttachment.m4a"];
}];
}
[_window.rootViewController presentViewController:messageController animated:YES completion:^{
}];
}];
}
-(void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
}
#end

i want navigate to another file in webview.

i want to call objective c file from javascript.
- (void)viewDidLoad
{
webview.delegate = self;
myButton.enabled = NO;
NSString *path=[[NSBundle mainBundle]pathForResource:#"1" ofType:#"html" inDirectory:#"files"];
NSURL *url=[NSURL fileURLWithPath:path];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[webview loadRequest:request];}
i am using this code to call my html page successfully and i use the below code to call shouldStartLoadWithRequest method in objective c.
<img src="cercle24px.png" />
now i went to call new TestViewController.m file how to i call this file, i used the below code.its print the nslog correctly and give alert box also.but doesn't navigate to next file.please help me if any one know.i am waiting for your valuable reply please.
- (BOOL)webView:(UIWebView*)webview shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"what");
UIAlertView *tstAlert = [[UIAlertView alloc] initWithTitle:#"" message:#"Allowed only alphabets and numeric" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[tstAlert show];
NSString *absoluteUrl = [[request URL] absoluteString];
NSLog(#"absolute%#",absoluteUrl);
if ([absoluteUrl isEqualToString:#"didtap://button1"]) {
NSLog(#"yes");
TestViewController *testview=[[TestViewController alloc]initWithNibName:#"TestViewController" bundle:nil];
[self.navigationController pushViewController:testview animated:YES];
return NO;
}
NSLog(#"no");
return YES;
}
Alright, I copy & tested your code, it works well, maybe somewhere else did wrong...
Create a new "Empty Template" Xcode project with ARC enabled, paste below into AppDelegat.m:
//
// AppDelegate.m
// WebTest
//
// Created by Elf Sundae on 8/5/13.
// Copyright (c) 2013 www.0x123.com. All rights reserved.
//
#import "AppDelegate.h"
#interface SampleViewController : UITableViewController
#end
#implementation SampleViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Sample Controller";
}
#end
#pragma mark -
#interface WebViewController : UIViewController <UIWebViewDelegate>
#end
#implementation WebViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.bounds];
web.delegate = self;
[self.view addSubview:web];
[web loadHTMLString:#"<a href='didTap://button1'><img src='cercle24px.png' /></a>" baseURL:nil];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:nil message:#"alert message" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
NSString *urlString = request.URL.absoluteString;
if ([urlString caseInsensitiveCompare:#"didtap://button1"] == NSOrderedSame) {
#define __use_method 3 // it could be: 1/2/3
#if (__use_method == 1)
SampleViewController *controller = [[SampleViewController alloc] init];
[self.navigationController pushViewController:controller animated:YES];
#elif (__use_method == 2)
/* method 2 */
SampleViewController *controller = [[SampleViewController alloc] init];
[self.navigationController performSelector:#selector(pushViewController:animated:)
withObject:controller
withObject:#(YES)];
#elif (__use_method == 3)
/* method 3 */
__unsafe_unretained __typeof(self) _self = self;
double delayInSeconds = 0.01;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
SampleViewController *controller = [[SampleViewController alloc] init];
[_self.navigationController pushViewController:controller animated:YES];
});
#endif
return NO;
}
return YES;
}
#end
#pragma mark -
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:
[WebViewController new]];
return YES;
}
#end

Array of sounds with .plist file?

Here is my code:
MainViewConroller.h
#import <UIKit/UIKit.h>
#import "FlipsideViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
AVAudioPlayer *audioPlayer;
NSArray *soundsArray;
}
#property(nonatomic, retain) AVAudioPlayer *audioPlayer;
#property(nonatomic, retain) NSArray *soundsArray;
-(void)prepareSounds;
- (IBAction)playSound:(UIButton *)sender;
#end
Here is my MainViewController.m:
#import "MainViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize audioPlayer;
#synthesize soundsArray;
-(void)prepareSounds
{
NSString *filepath= [[NSBundle mainBundle] pathForResource:#"Sound" ofType:#"plist"];
self.soundsArray = [[NSArray alloc] initWithContentsOfFile:filepath];
}
- (void)stopAudio
{
if (audioPlayer!= nil) {
[audioPlayer stop];
//do some task for changing the Image i.e setting the default image
}
}
- (IBAction)playSound:(UIButton *)sender
{
UIButton *btn = (UIButton*)sender;
NSString *soundName = [soundsArray objectAtIndex:(btn.tag - 1)];
NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:#"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *p = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
self.audioPlayer = p;
if([audioPlayer isPlaying])
{
[self stopAudio];
}
[self.audioPlayer play];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Flipside View
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)showInfo:(id)sender
{
FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:#"FlipsideViewController" bundle:nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:controller animated:YES completion:nil];
}
#end
I have 3 buttons. In the 'Supporting Files' folder I have an array of strings with the name of the sound files I want to play, named 'Sound.plist', and in the 'Supporting Files' folder I have a folder named 'Sounds', which contains the sound files.
All of my buttons play the same sound, even when I delete the .plist file. It seems to always play the sound that is first in the 'Sounds' folder. Can someone please provide some insight, I feel like I have tried everything. Thanks!

Playing a Sound While App Runs

EDITED
still not sure whats wrong please help
hi there I'm creating and iOS application and trying to make it play a sound when running I've type up my code in the app delegate .h , .m and it plays the sound fine but the thing is it goes to a black screen when my ViewController.xib has a blue background heres heres the code i have
AppDelegate.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#class ViewController;
#interface AppDelegate : NSObject <UIApplicationDelegate, AVAudioPlayerDelegate> {
UIWindow *window;
ViewController *viewController;
AVAudioPlayer *_backgroundMusicPlayer;
BOOL _backgroundMusicPlaying;
BOOL _backgroundMusicInterrupted;
UInt32 _otherMusicIsPlaying;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ViewController *viewController;
- (void)tryPlayMusic;
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Set up the audio session
// See handy chart on pg. 55 of the Audio Session Programming Guide for what the categories mean
// Not absolutely required in this example, but good to get into the habit of doing
// See pg. 11 of Audio Session Programming Guide for "Why a Default Session Usually Isn't What You Want"
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
// Create audio player with background music
NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:#"ticktock" ofType:#"wav"];
NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
_backgroundMusicInterrupted = YES;
_backgroundMusicPlaying = NO;
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player {
if (_backgroundMusicInterrupted) {
[self tryPlayMusic];
_backgroundMusicInterrupted = NO;
}
}
- (void)applicationDidBecomeActive:(NSNotification *)notification {
[self tryPlayMusic];
}
- (void)tryPlayMusic {
// Play the music if no other music is playing and we aren't playing already
if (_otherMusicIsPlaying != 1 && !_backgroundMusicPlaying) {
[_backgroundMusicPlayer prepareToPlay];
[_backgroundMusicPlayer play];
_backgroundMusicPlaying = YES;
}
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
ok so thats all the code
and heres what i get when app loads and the sound works fine
and this is what i want to get (ViewController.xib)
Thank in advanced
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
self.viewController = [[ViewController alloc] init];
// Create audio player with background music
NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:#"ticktock" ofType:#"wav"];
NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
new code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
You never initialized your view controller.
Somewhere before you do
[window addSubview:viewController.view];
You need to do
self.viewController = [[ViewController alloc] init];
I see that you declared the property as an IBOutlet.. is it actually hooked up to something in Interface Builder?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
// Create audio player with background music
NSString *ticktockPath = [[NSBundle mainBundle] pathForResource:#"ticktock" ofType:#"wav"];
NSURL *ticktockURL = [NSURL fileURLWithPath:ticktockPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:ticktockURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Copy that function and just delete this one - (void)applicationDidFinishLaunching:(UIApplication *)application completely.
You should also consider converting your project to use ARC. It will remove the need to retain/release/autorelease statements.
You have two targets - are all your resources included in the target that you're building?

Resources