I am using AVAudioPlayer to play an audio file its working but on some device it does not play how do i solve my problem
if(_defaultSettings)
{
_soundFilePath = [[NSBundle mainBundle] pathForResource:#"ring" ofType:#"wav"];
NSLog(#"ringTone Path%#",_soundFilePath);
// /System/Library/Audio/UISounds/
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:_soundFilePath ]error:nil];
[_audioPlayer prepareToPlay];
[_audioPlayer play];
_audioPlayer.numberOfLoops = -1;
AudioServicesPlaySystemSound(1000);
}
- (void)playSystemSound {
NSLog(#"playSystemSound");
// Create the URL for the source audio file. The URLForResource:withExtension: method is
// new in iOS 4.0.
NSURL *tapSound = [[NSBundle mainBundle] URLForResource: #"short_low_high"
withExtension: #"wav"];
if (!self._soundFileURLRef) {
// Store the URL as a CFURLRef instance
self._soundFileURLRef = (CFURLRef) [tapSound retain];
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (_soundFileURLRef, &_soundFileObject);
}
// Play the sound
AudioServicesPlaySystemSound (_soundFileObject);
// // to vibrate the device // AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
}
Related
I want to play a audio on Button click. I have tried this code but audio is not playing:-
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"sound" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:soundFileURL error:nil];
audioPlayer.delegate = self;
audioPlayer.volume=1.0;
[audioPlayer setNumberOfLoops:1];
[audioPlayer play];
you haven't created a player item
//declare in .h file
AVPlayerItem *playerItem;
//then in .m file
player = [AVPlayer playerWithPlayerItem:playerItem];
after that play it
[player play];
First, it appears you are using initWithData to access an audio file pointed to by a URL.
You should instead use initWithContentsOfU‌RL.
Another issue could be due to a common error in implementing the audio player.
If the AVAudioPlayer you are creating is inside a function, it will be released, or deallocated, at the end of the function. This is why the audio does not play.
To fix this problem, make the AVAudioPlayer a property or instance variable in your class so that it does not get immediately deallocated.
For example, a property is declared in your header as
#property(strong, nonatomic) AVAudioPlayer *audioPlayer;
and initialized in your implementation with
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:soundFileURL error:nil];
If this does not solve your problem, then the issue is likely to do with the file pointed to by your URL.
NSString *soundFilePath = [NSString stringWithFormat:#"%#/test.mp3",
[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite
[player play];
print "soundFileURL" . check whether it is null(in case soundFileURL contains spaces it results/prints null ) and if it not a null value check the file name is spelled exactly correct or not(i.e., here your file name is "sound")
var asyncaAudioPlayer: AVAudioPlayer!
let audioFilePath = NSBundle.mainBundle().pathForResource(fileName, ofType: "mp3")
let audioFileUrl = NSURL.fileURLWithPath(audioFilePath!)
asyncaAudioPlayer = AVAudioPlayer(contentsOfURL: audioFileUrl, fileTypeHint: nil)
audioPlayerArray.append(asyncaAudioPlayer)
asyncaAudioPlayer.prepareToPlay()
asyncaAudioPlayer.play()
Your problem is you set NSURL for initWithData -> Wrong.
in case it sound play multi time, you should prepare your sound Data and keep it as strong ref.
and you should use CGD and global queue instead of main queue.
-(void)onTouchUpInside{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:self.soundFileData error:nil];
audioPlayer.delegate = self;
audioPlayer.volume=1.0;
[audioPlayer setNumberOfLoops:1];
if ([audioPlayer prepareToPlay] && [audioPlayer play])
{
NSLog(#"play Success!");
}
else
{
NSLog(#"Failed to play the audio file.");
}
});
}
I have read some threads about this topic, and currently have this:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *soundFilePath = [NSString stringWithFormat:#"%#/testsoundsr.aiff",
[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath: soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
error:nil];
player.numberOfLoops = -1; //Infinite
[player play];
}
The sound is not played though, and I can only imagine that the problem is with the NSString definition which is used to reference the file
The file I'm trying to play is named 'testsoundsr.aiff' and I have dragged that into the project. Also I have added several frameworks to the project, including AudioToolBox.framework
---UPDATE---
I have now tried using an .mp3 file instead, but still getting no sound through.
Try player.delegate = self before [player play]
Hi in my application, audio is playing when user press the button but now I have two audio buttons like audio1 and audio2, now I want to play second audio after a time interval once the audio1 is completed by clicking the same button.
- (IBAction)btn1:(id)sender {
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"audio" ofType:#"mp3" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.audioPlayer play];
}
The above code I have used for play one audio now I want to play second audio once the first audio completed please tell me how to make it.
Thanks.
Try this:
You have to add a bool variable with the name 'firstAudioPlayed' on start the variable should be NO or FALSE.
- (IBAction)btn1:(id)sender {
if (![self.audioPlayer isPlaying]) {
NSString *audioPath;
if (self.firstAudioPlayed) {
audioPath = [[NSBundle mainBundle] pathForResource:#"audio2" ofType:#"mp3" ];
} else {
audioPath = [[NSBundle mainBundle] pathForResource:#"audio1" ofType:#"mp3" ];
}
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.audioPlayer play];
self.firstAudioPlayed = !self.firstAudioPlayed;
}
}
I'm not sure if it's working like this, else just ask with a comment...
Explication of the code:
First you check if the player is already playing a song, if he isn't, you check if the first audio already has played (self.firstAudioPlayed) with this you can give the correct path to load the audio file. Now you play this audio file.
(Sorry for my grammar and my english, corrections are welcome)
You probably should use player's delegate. Set audioPlayer.delegate=self; and implement audioPlayerDidFinishPlaying:successfully: method to see when a player finished playing.
Then you can do whatever you want in there, for example start the second audio.
My client wants to create an app in which user can play 4 audio at once and then start start any audio and then record them as one file.
I have not worked on audio/video apps so i want to know that is that possible in ios sdk?
How many audio file can be played at same time?
You can play many musics at the same time using AVAudioSession.
UInt32 allowMixing = true;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(allowMixing), &allowMixing);
You can play multiple audio file with this code
NSString *songA = [[NSBundle mainBundle] pathForResource:#"songA" ofType:#"mp3"];
NSError *soundError = nil;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:songA] error:&soundError];
if(self.player == nil)
NSLog(#"%#",soundError);
else
{
[self.player setDelegate:self];
[self.player setVolume:0.75];
[self.player play];
}
NSString *songB = [[NSBundle mainBundle] pathForResource:#"songB" ofType:#"mp3"];
soundError = nil;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:songB] error:&soundError];
if(self.player == nil)
NSLog(#"%#",soundError);
else
{
[self.player setDelegate:self];
[self.player setVolume:0.25];
[self.player play];
}
To marge more than one audio file you can use ans from this question Combining two .caf files on iPhone
I am working on Playing an audio file stored in Document Directory using AVAudioPlayer.The Audio exists in directory and has 82 bytes of size.
I want to detect whether this audio is Playable or not.
/*save the Audio file in Document Directory */
NSFileManager *fileManager=[NSFileManager defaultManager];
/*Get the Path to Application Documents Directory*/
NSArray *docDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
/*append the neccessary file extension */
NSLog(#"%d",bt.tag);
int a=bt.tag-10000;
NSString *filepathStr=[NSString stringWithFormat:#"/%#/%#.mp3",docDir,[NSString stringWithFormat:#"%d",a]];
/*Check if my crrent file exists in the Documents Directory*/
if([fileManager fileExistsAtPath:filepathStr])
{
NSData *dat = [fileManager contentsAtPath:filepathStr];
NSLog(#"data is %d",[dat length]);
if(player)
{
[player stop];
[player release];
player=nil;
}
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:filepathStr] options:nil];
/* You can then check its playable property:*/
if (asset.playable)
{
player = [[AVAudioPlayer alloc] initWithData:dat error:nil];
player.delegate = self;
[player play];
//Do Something
}
I have other playable audios also stored in Document directory those are playing fine.
I have used the AVURLAsset and tried to check its property "playable" but couldn't succeed as the AVURLAsset object is not formed.
This audio file has a size of 82 bytes but its not playing not even in the itunes.
I just found the solution to this we can detect the audio is playable or not by using the following code
NSURL *url=[[NSURL alloc] initFileURLWithPath:filepathStr];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
/* You can then check its playable property:*/
if (asset.playable)
{
player = [[AVAudioPlayer alloc] initWithData:dat error:nil];
player.delegate = self;
[player play];
}