I have this method to play an mp3:
- (void) playSound:(NSString*)sound{
NSString *path = [NSString stringWithFormat:#"%#/%#",
[[NSBundle mainBundle] resourcePath],
sound];
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:nil];
[player prepareToPlay];
[player play];
}
everytime I call this method I get a new string "sound" and then I must alloc everytime this AVAudioplayer "player"; I want release it when I stop it or when it finish...is it possible?
Try the below instruction
yourViewController.h
#interface yourViewController : UIViewController <AVAudioPlayerDelegate>
yourViewController.m file for add function
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//play finished
}
Declare the AVAudioPlayer Object below code
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL
fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"audio" ofType:#"mp3"]] error:NULL];
audioPlayer.delegate = self;
audioPlayer.currentTime=0.0f;
[audioPlayer prepareToPlay];
[audioPlayer play];
Thanks..!
Take a look at AVAudioPlayerDelegate.
It has the methods audioPlayerDidFinishPlaying:successfully: and audioPlayerDecodeErrorDidOccur:error: that should let you do what you want.
Related
For some reason, the cleanupPlayer method is a little buggy and isn't releasing the audio player correctly. My application crashes from time to time, and I suspect it's due to a memory issue. Also, when I try to play an audio file twice (on button click), the second time the audio sometimes cuts out. I'm a bit of a newbie, so any help would be greatly appreciated!
Here is a snippet of code:
.h file:
#property (retain,nonatomic)AVAudioPlayer *player;
.m file:
-(void)playSound:(NSString *)fileName
{
// Play
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:kSoundFileType]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
if(_player != nil) {
[_player release];
}
try this...
-(void)playSound:(NSString *)fileName
{
if (_player.isPlaying) {
[_player stop];
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"]];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
_player.delegate = self;
[_player prepareToPlay];
[_player play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self cleanupPlayer];
}
-(void)cleanupPlayer
{
_player =nil;
}
I'm following in a tutorial on how to play mp3 sounds when pressing a button.
I created a button (playSound).
I added it to the view controller interface:
- (IBACTION)playSound:(id)sender;
in the implementation I declared the needed header files and I wrote the following:
#import "AudioToolbox/AudioToolbox.h"
#import "AVFoundation/AVfoundation.h"
- (IBAction)playSound:(id)sender {
//NSLog(#"this button works");
AVAudioPlayer *audioPlayer;
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"audio" ofType:#"mp3"];
//NSLog(#"%#", audioPath);
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
//NSLog(#"%#", audioURL);
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
[audioPlayer play];
}
I'm not getting any errors. the NSlogs are logging the URL fine, and now I have no clue where to look further. I also checked if my MP3 sound was maybe damaged, but that was also not the case. all i hear is a little crackling noise for 1 second. then it stops.
You declared a local variable audioPlayer to hold a pointer to the player. As soon as your button handler returns the player is being released before it has a chance to play your sound file. Declare a property and use it instead of the local variable.
In YourViewController.m file
#interface YourViewController ()
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
#end
or in YourViewController.h file
#interface YourViewController : UIViewController
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
#end
Then replace audioPlayer with self.audioPlayer in your code.
try this its working for me
in .h
AVAudioPlayer * _backgroundMusicPlayer;
in .m
NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:#"Theme" ofType:#"mp3"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1];
[_backgroundMusicPlayer play];
Edited
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.delegate=self;
[audioPlayer play];
Try this and let me know. Make sure you set the delegate for audioPlayer.
Firstly re add your music file in your project , then try this code
With the log you can see error.
NSError *error;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"bg_sound" ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error){
//Print Error
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer setNumberOfLoops: -1];
[audioPlayer play];
audioPlayer.volume=1.0;
}
Make sure your music files are properly added in project
I've an AVAudioPlayer with a MP3-file. But before playing, you'll hear a hitch.
This is my code:
NSString *geluid = [NSString stringWithFormat:#"RG_%#", nummer];
NSString *path = [[NSBundle mainBundle] pathForResource:geluid ofType:#"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate=self;
[theAudio prepareToPlay];
[theAudio play];
NSURL *url = [NSURL fileURLWithPath:path];
avplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[avplayer prepareToPlay];
[avplayer play];
For example: You hear "Ssstop here", in stead off "Stop here".
Please help me to fix it.
Is this code running two AVAudioPlayer instances at the same time ?
Why are you using both avplayer and theAudio ?
From looking at it it looks like you should get rid of one of them...
- (void)viewDidLoad {
[super viewDidLoad];
[audioPlayer stop];
NSString *Path = [[NSBundle mainBundle] pathForResource:#"Keep the Shoes Moving" ofType: #"m4a"];
NSURL *URL = [[NSURL alloc] initFileURLWithPath: Path];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; }
What happens with this is every time I navigate back to this viewController it plays another track. So then I have two tracks playing over each other. How would I get this to stop??
Store your AVAudioPlayer instance in a property and call it’s stop method when you want it to stop playing.
I want to play a sound when a button is pressed. I tried this:
-(void)PlayClick
{
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"BubblePopv4"
ofType:#"mp3"]];
AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[click play];
}
…and imported #import <AudioToolbox/AudioToolbox.h> and #import <AVFoundation/AVFoundation.h>
but for some reason the sound is not playing. The name and type are right because the file I added to the project is "BubblePopv4.mp3". The volume on the iPad is on maximum, and the sound plays fine on iTunes! Any ideas?
Leave it, Don't do it in a new Class, simple stuff for you:
- (void)playSoundWithOfThisFile:(NSString*)fileNameWithExtension {
// Eg - abc.mp3
AVAudioPlayer *audioPlayerObj;
NSString *filePath;
filePath= [[NSString stringWithFormat:#"%#", [[NSBundle mainBundle] resourcePath]] retain];
if(!audioPlayerObj)
audioPlayerObj = [AVAudioPlayer alloc];
NSURL *acutualFilePath= [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#",filePath,fileNameWithExtension]];
NSError *error;
[audioPlayerObj initWithContentsOfURL:acutualFilePath error:&error];
[audioPlayerObj play];
}
Do this:
In .h file:
Use this delegate - <AVAudioPlayerDelegate>
#import "AVFoundation/AVAudioPlayer.h"
AVAudioPlayer *audioPlayerObj;
NSString *filePath;
In .m file , In some method:
filePath= [[NSString stringWithFormat:#"%#", [[NSBundle mainBundle] resourcePath]] retain];
if(!audioPlayerObj)
audioPlayerObj = [AVAudioPlayer alloc];
And add these two methods:
- (id)initWithFileName:(NSString*)fileNameWithExtension {
if ((self = [super init])) {
NSURL *acutualFilePath= [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#",filePath,fileNameWithExtension]];
NSError *error;
[audioPlayerObj initWithContentsOfURL:acutualFilePath error:&error];
}
return self;
}
- (void)playSound {
[audioPlayerObj play];
}
You can pass the filename to this Method - initWithFileName
and then call playSound method to play sound for you.
Hope this helps.
Replace url initialization with:
NSURL* musicFile = [NSURL initFileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"BubblePopv4"
ofType:#"mp3"]];