How do I play audio when my ios app starts? - objective-c

I have been following tutorials and looking at other posts but I can't seem to get audio to start playing automatically when my app starts.
I want the wav file to just keep playing in the background and looping. I do NOT want start and stop controls etc...
Below is the code I have in my ViewController.m file (is this the right place?) and I have added the AVFoundation.frameowrk and imported it to my .m file. Additionally I have added my wav file called AlienRoom to my supporting files. Any help would be awesome! I am new so please go step by step or make it real clear if you can. Thank you!!!
p.s. I haven't added the code to make it loop so any help there would be great too!
//play background sound upon opening app
-(void) awakeFromNib
{
NSString *path = [[NSBundle mainBundle] pathForResource: #"AlienRoom" ofType: #"wav"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
}

Implement AVAudioPlayerDelegate in ViewController.h
#interface ViewController : UIViewController <AVAudioPlayerDelegate>
#property(nonatomic,strong)AVAudioPlayer *theAudio;
ViewController.m file
-(void)viewWillAppear:(BOOL)animated
{
NSString *path = [[NSBundle mainBundle] pathForResource: #"AlienRoom" ofType: #"wav"];
if(!self.theAudio)
self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
self.theAudio.delegate = self;
[self.theAudio play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)data successfully:(BOOL)flag{
[NSThread detachNewThreadSelector:#selector(playAudioAgain) toTarget:self withObject:nil];
}
- (void)playAudioAgain{
[self.theAudio play];
}
-(void)viewWillDisappear:(BOOL)animated
{
if(self.theAudio.isPlaying)
{
self.theAudio.delegate = nil;
[self.theAudio stop];
}
}

Related

AVAudioPlayer problems - no issues but doesn't work

To play a button sound when button tapped, I use AudioToolbox and AVFoundation.
I import these in my .h using
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
Via storyboard, I connected a UIButton to a new IBAction and then included the following in my .m
- (IBAction)playSound11:(id)sender {
//Load an audio file from the bundle
NSString *audioFile = [[NSBundle mainBundle] pathForResource:#"11" ofType:#"mp3"];
//Convert string to NSURL
NSURL *audioURL = [NSURL fileURLWithPath:audioFile];
//Initialize an audio player with the mp3 URL
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
// Start playing
[player play];
}
I get no issues and the app does open but there is no sound at all.
What am I doing wrong?
Problem with your URL perhaps?
This is how I use it
NSURL *audioURL = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/11.mp3", [[NSBundle mainBundle] resourcePath]]];

Play Audio iOS Objective-C

I'm trying to get an audio file playing in my iOS app. This is my current code
NSString *soundFilePath = [NSString stringWithFormat:#"%#/test.m4a", [[NSBundle mainBundle] resourcePath]];
NSLog(#"%#",soundFilePath);
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer setVolume:1.0];
audioPlayer.delegate = self;
[audioPlayer stop];
[audioPlayer setCurrentTime:0];
[audioPlayer play];
I've being checking a bunch of other posts but they all generally do the same thing. I'm not getting an error, but I don't hear any audio playing on the simulator or device.
This is the path I get for the audio file on the simulator
/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/long-numbered-thing/BookAdventure.app/test.m4a
Any help is appreciated!
Maybe you should try using the NSBundle method pathForResource:ofType: method to create the path to the file.
The following code should successfully play an audio file. I have only used it with an mp3, but I imagine it should also work with m4a. If this code does not work, you could try changing the format of the audio file. For this code, the audio file is located in the main project directory.
/* Use this code to play an audio file */
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite
[player play];
EDIT
Ok, so try this:
NSString *soundFilePath = [NSString stringWithFormat:#"%#/test.m4a",[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite
[player play];
Also, make sure you do the proper imports:
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
You need to store a strong reference to 'AVAudioPlayer'
#property (strong) AVAudioPlayer *audioPlayer;
And if you are sure that your audio file is in following Bundle Resources, it should play.
Project>Build Phases>Copy
To play file with extension .caf, .m4a, .mp4, .mp3,.wav, .aif
Download following two files from GitHub
SoundManager.h
SoundManager.m
Add these files to your project
Also add audio files to resource folder (sample files)
mysound.mp3, song.mp3
Import header file in desired file
#import "SoundManager.h"
And add following two lines in -(void)viewDidLoad
[SoundManager sharedManager].allowsBackgroundMusic = YES;
[[SoundManager sharedManager] prepareToPlay];
Use following line to play sound (mysound.mp3)
[[SoundManager sharedManager] playSound:#"mysound" looping:NO];
Use following line to stop the sound (mysound.mp3)
[[SoundManager sharedManager] stopSound:#"mysound"];
Also you can play music (song.mp3) as
[[SoundManager sharedManager] playMusic:#"song" looping:YES];
And can be stop music as
[[SoundManager sharedManager] stopMusic];
Complete Documentation is on GitHub
First import this framework to your file
#import <AVFoundation/AVFoundation.h>
Then declare an instance of AVAudioPlayer.
AVAudioPlayer *audioPlayer;
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"Name of your audio file"
ofType:#"type of your audio file example: mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
To play your bundle audio file using below code if you generate the system sound ID
for(int i = 0 ;i< 5;i++)
{
SystemSoundID soundFileObject;
NSString *audioFileName = [NSString stringWithFormat:#"Alarm%d",i+1];
NSURL *tapSound = [[NSBundle mainBundle] URLForResource: audioFileName
withExtension: #"caf"];
// Store the URL as a CFURLRef instance
CFURLRef soundFileURLRef = (__bridge CFURLRef) tapSound;
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (
soundFileURLRef,
&soundFileObject
);
[alarmToneIdList addObject:[NSNumber numberWithUnsignedLong:soundFileObject]];
}
You can play the sound by using below code
AudioServicesPlaySystemSound([[alarmToneIdList objectAtIndex:row]unsignedLongValue]);
To achieve this below framework need to add in your Xcode
AudioToolbox
Finally below header files are needs to be import in controller
#import AudioToolbox/AudioToolbox.h
#import AudioToolbox/AudioServices.h
Updated for Swift 4
Playing from main bundle
- iOS 11 only
import AVFoundation
var player: AVAudioPlayer?
The following code loads the sound file and plays it, returning an error if necessary.
guard let url = Bundle.main.url(forResource: "test", withExtension: "m4a") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
guard let player = player else { return }
player.play()
} catch let error {
// Prints a readable error
print(error.localizedDescription)
}
Swift 4.2
var soundFilePath = "\(Bundle.main.resourcePath ?? "")/test.m4a"
var soundFileURL = URL(fileURLWithPath: soundFilePath)
var player = try? AVAudioPlayer(contentsOf: soundFileURL)
player?.numberOfLoops = -1 //Infinite
player?.play()

background music

(using AVFoundation.framework)
#import "AVFoundation/AVFoundation.h"
So I got a problem, I tried this code first in init method of my class (that is the one that is loaded first)
NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"];
NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops=-1;
[player play];
But it didn't work, than I decided to do it in thread:
in init method:
[NSThread detachNewThreadSelector:#selector(playMusic) toTarget:self withObject:nil];
and method itself:
-(void) playMusic {
NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"];
NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops=-1;
[player play];
}
it is declared in *.h file of course. It also didn't work.
I tried to debug, on line
}
of playMusic method the file is played for 2 or 3 seconds and then stops. It isn't played without debug. What is the problem?
The AVAudioPlayer will be deallocated immediately. You need to retain the player.
So make the AVAudioPlayer an instance variable of the class.

How to release the AVAudioPlayer in the below code

I want to release the memory which I allocated for AVAudioPlayer, but when I tried to release it then the sound is not playing.It is potential memory leak, how can I get out of this.
here the below code is used when wrong selection is picked then I am playing the error sound, If I select multiple time wrong selection then It is allocated multiple times then how can I rid out of this.
else
{
NSString *soundName=#"Error.mp3";
NSError *error;
NSURL *urlString = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%s", [[NSBundle mainBundle] resourcePath],[soundName UTF8String]]];
AVAudioPlayer *worngAudioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:urlString error:&error];// here I also used to release using autorelease then not played sound
worngAudioPlay.delegate = self;
if (worngAudioPlay == nil)
{
}
else
{
[worngAudioPlay play];
}
// [worngAudioPlay release]; // Here I released then not played sound
}
Thank you,
Madan Mohan.
you can release in avaudio player delegate method named audioDidFinishPlaying. I don't know the name exactly. but you might get an idea what I am talking about
Make it a retained property of your class, and release it in the dealloc.
In your header file:
#property(retain)AVAudioPlayer *player;
In your implementation (.m) file:
#synthesize player;
In your code above:
else
{
NSString *soundName=#"Error.mp3";
NSError *error;
NSURL *urlString = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%s", [[NSBundle mainBundle] resourcePath],[soundName UTF8String]]];
AVAudioPlayer *worngAudioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:urlString error:&error];
if (worngAudioPlay != nil)
{
// this will cause the previous one to be released
[self setPlayer:worngAudioPlay];
[worngAudioPlay release];
worngAudioPlay.delegate = self;
[worngAudioPlay play];
}
}
In your dealloc:
-(void)dealloc {
[player release];
[super dealloc];
}

Can I play loops using Audio Toolbox?

in my app i use AudioToolbox framework and i need to play a loop can i ?
this is the AVAudioplayer code that goes slowly with 2 touches simultaneously
- (AVAudioPlayer *)getNoteFromFilename:(NSString *)name andoftype:(NSString *)type{
NSString *soundPath = [[NSBundle mainBundle] pathForResource:name
ofType:type];
NSURL *fileURL = [NSURL fileURLWithPath:soundPath];
AVAudioPlayer *note = [[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL
error:nil] autorelease];
return note;
}
in the viewdidload
ViewDidLoad {
self.Note = [self getNoteFromFilename:#"Note" andoftype:#"wav"];
}
calling it by this in IBAction :
[Note prepareToPlay];
[Note play];
NB: i have retaind all the button and the AVAudioPlayer
Use AVAudioPlayer instead. There you can easily loop using the numberOfLoops property.