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;
}
Related
I ran the allocations instruments and I definitely have a retain cycle, the stairs-like graph is a dead giveaway. However, I'm new to iOS programming and have no idea how to fix my retain cycle issue even after sifting through the internet for documentation. To my knowledge there are some strong references that are preventing unused memory from being deallocated in my ARC project. The app is a simple soundboard but has a lot of content, which is why I haven't had to deal with this issue before. Memory is a real problem now. For ViewController.m I have
#import GoogleMobileAds;
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController () <GADInterstitialDelegate, UIAlertViewDelegate>
{
AVAudioPlayer *_audioPlayer;
}
#property(nonatomic, strong) GADInterstitial *interstitial;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createAndLoadInterstitial];
BannerManager *sharedManager = [BannerManager sharedManager];
GADBannerView* bView = [sharedManager setupBannerAds:self.view];
bView.delegate = self;
bView.rootViewController = self;
GADRequest *request = [GADRequest request];
[bView loadRequest:request];
}
- (void)adViewDidReceiveAd:(GADBannerView *)bannerView {
NSLog(#"adViewDidReceiveAd: %#", bannerView.adNetworkClassName);
}
int counter = 0;
#pragma Interstitial button actions
- (IBAction)playAgain:(id)sender {
if (counter % 15 == 0) {
if (self.interstitial.isReady) {
[self.interstitial presentFromRootViewController:self];
} else {
}
}
counter++;
}
- (void)createAndLoadInterstitial {
self.interstitial =
[[GADInterstitial alloc] initWithAdUnitID:#"mygoogleidgoeshere"];
self.interstitial.delegate = self;
GADRequest *request = [GADRequest request];
[self.interstitial loadRequest:request];
}
#pragma mark GADInterstitialDelegate implementation
- (void)interstitial:(GADInterstitial *)interstitial
didFailToReceiveAdWithError:(GADRequestError *)error {
NSLog(#"interstitialDidFailToReceiveAdWithError: %#", [error localizedDescription]);
}
- (void)interstitialDidDismissScreen:(GADInterstitial *)interstitial {
NSLog(#"interstitialDidDismissScreen");
[self createAndLoadInterstitial];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)areyoufinishedyet:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"areyoufinishedyet"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)areyoulooking:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"areyoulooking"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)blueeyes:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"blueeyes"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)crosshairs:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"crosshairs"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)doyoumind:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"doyoumind"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)dontblink:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"dontblink"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)growontrees:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"growontrees"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)iamagenius:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"iamagenius"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];}
- (IBAction)imarealboy:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"imarealboy"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)importantbusiness:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"importantbusiness"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)inmyeye:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"inmyeye"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)justblinked:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"justblinked"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)mustyoureally:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"mustyoureally"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)nottheenemy:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"nottheenemy"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)oddlyenough:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"oddlyenough"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];}
- (IBAction)staringcontest:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"staringcontest"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];
}
- (IBAction)youreaklutz:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"youreaklutz"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];}
- (IBAction)youreamoron:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"youreamoron"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];}
- (IBAction)yourepissingmeoff:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"yourepissingmeoff"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];}
- (IBAction)challengeme:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"challengeme"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];}
- (IBAction)forerunners:(id)sender {
soundFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"forerunners"
ofType:#"mp3"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.delegate = self;
[sound play];}
and for Viewcontroller.h I have
#import <UIKit/UIKit.h>
#import "BannerManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import GoogleMobileAds;
#interface ViewController: UIViewController<GADBannerViewDelegate, AVAudioPlayerDelegate> {
NSURL *soundFile;
AVAudioPlayer *sound;
}
//343 GUILTY SPARK
- (IBAction)areyoufinishedyet:(id)sender;
- (IBAction)areyoulooking:(id)sender;
- (IBAction)blueeyes:(id)sender;
- (IBAction)crosshairs:(id)sender;
- (IBAction)doyoumind:(id)sender;
- (IBAction)dontblink:(id)sender;
- (IBAction)growontrees:(id)sender;
- (IBAction)iamagenius:(id)sender;
- (IBAction)imarealboy:(id)sender;
- (IBAction)importantbusiness:(id)sender;
- (IBAction)inmyeye:(id)sender;
- (IBAction)justblinked:(id)sender;
- (IBAction)mustyoureally:(id)sender;
- (IBAction)nottheenemy:(id)sender;
- (IBAction)oddlyenough:(id)sender;
- (IBAction)staringcontest:(id)sender;
- (IBAction)youreaklutz:(id)sender;
- (IBAction)youreamoron:(id)sender;
- (IBAction)yourepissingmeoff:(id)sender;
//ARBITER
- (IBAction)challengeme:(id)sender;
- (IBAction)forerunners:(id)sender;
- (IBAction)halospurpose:(id)sender;
- (IBAction)imgoingtocutit:(id)sender;
- (IBAction)imprepared:(id)sender;
- (IBAction)readytofight:(id)sender;
- (IBAction)sacredrings:(id)sender;
- (IBAction)saveyouranger:(id)sender;
- (IBAction)youshotmefoo:(id)sender;
- (IBAction)tararusstop:(id)sender;
- (IBAction)trymypatience:(id)sender;
- (IBAction)whatyouwant:(id)sender;
- (IBAction)arbiterdo:(id)sender;
//BRUTES
- (IBAction)adaysrations:(id)sender;
- (IBAction)atinymorsel:(id)sender;
- (IBAction)bastardelite:(id)sender;
- (IBAction)boilinyourpot:(id)sender;
- (IBAction)cannedmeat:(id)sender;
- (IBAction)cannotescape:(id)sender;
this is only part of the code because the rest is pretty huge, and is basically the same line of code over and over with minor changes to the files it references. My question is how in the world do I fix retain cycles? Is it something to do with my modal transitions? Because this is what's causing crazy memory allocation in instruments and crashes on my native iOS device.
It sounds to me like you don't have a retain cycle, exactly. It sounds like you are presenting a never-ending series of view controllers on top of other view controllers.
Using a modal present or a navigation controller push has a similar effect: The previous view controller gets covered with a new one but does not get freed.
You didn't post any of the code that shows how you navigate from view controller to view controller, so it's hard to tell what you're doing exactly.
If you want to go from view controller A to view controller B to view controller C, then back to A, you need to present from A to B, then from B to C, but dismiss in order to get back, not present a new copy of view controller A.
I have a very simple app that is supposed to only play an audio file on view. Instead my Xcode is crashing.
I am using Xcode version 6. I have implemented the AVFoundation Framework
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"Crowd_cheering"
ofType:#"m4a" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.player play];
}
//Try like this with error condition:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Moderato"
ofType:#"mp3"]];
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];
}
//Before that add import AVFoundation/AVFoundation.h and add delegate AVAudioPlayerDelegate
//then Implement the AVAudioPlayerDelegate Protocol Methods like this
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
}
Make sure u connected ur play button properly or not and also check whether you Added an Audio File to the Project Resources properly.
I'm trying to play remote .mp3 file
but its giving the following error.
The operation couldn’t be completed. (OSStatus error -43.)
here is my code :
- (void)viewDidLoad
{
[super viewDidLoad];
isPlaying = NO;
/*
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Dar-e-Nabi-Per" ofType:#"mp3"]];
*/
NSURL *url = [NSURL
URLWithString:#"http://megdadhashem.wapego.ru/files/56727/tubidy_mp3_e2afc5.mp3"];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
}
else
{
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
}
Can anyone please guide me where i'm doing mistake
For steaming audio from a remote server, use AVPlayer instead of AVAudioPLayer.
AVPlayer Documentation
Sample Code:
- (void)playSampleSong:(NSString *)iSongName {
NSString *aSongURL = [NSString stringWithFormat:#"http://megdadhashem.wapego.ru/files/56727/tubidy_mp3_e2afc5.mp3"];
// NSLog(#"Song URL : %#", aSongURL);
AVPlayerItem *aPlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:aSongURL]];
AVPlayer *anAudioStreamer = [[AVPlayer alloc] initWithPlayerItem:aPlayerItem];
[anAudioStreamer play];
// Access Current Time
NSTimeInterval aCurrentTime = CMTimeGetSeconds(anAudioStreamer.currentTime);
// Access Duration
NSTimeInterval aDuration = CMTimeGetSeconds(anAudioStreamer.currentItem.asset.duration);
}
Use this to play song from URL
NSData *songData=[NSData dataWithContentsOfURL:url];
self.player = [[AVAudioPlayer alloc] initWithData:songData error:nil];
self.player.numberOfLoops=0;
_player.delegate=self;
[_player prepareToPlay];
[_player play]
sorry for my question but i´ve implemented a intro- video and despite of the hardware silent-switch of my iPad, the audio is playing.
I´m also using the AVAudioplayer within my app just for playing short sound samples. Within this class, its the only region where i´ve set up the "AVAudioSessionCategory".
But for all audio playback only, there´s nothing hearable. Its just for my intro-video.
Any help how to fix that "audio-bug" so the movie player is silent?
Thanks you
Here´s my Audio-class:
- (id)initWithSoundfileName:(NSString*) file
{
if ((self = [super init]))
{
NSString* filename = [file stringByDeletingPathExtension];
NSString* fileextension = [file pathExtension];
// get file path from bundle
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: filename ofType: fileextension];
NSLog(#"AudioPlayer init: %#", soundFilePath);
NSURL* fileurl = [[NSURL alloc] initFileURLWithPath:soundFilePath];
NSError* error = nil;
AVAudioPlayer* audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileurl error:&error ];
if (error) { NSLog(#"Error creating AVAudioPlayer %#", [error description]);}
// set audio policy
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:NULL];
self.player = audioplayer;
[self.player prepareToPlay];
[self.player setDelegate:self];
}
return self;
}
-(void) play{
[self.player play];
}
And here´s my video-playback method:
- (void)playIntroVideo
{
NSString *movpath = [[NSBundle mainBundle] pathForResource:#"mymovie" ofType:#"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:movpath];
self.moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
self.moviePlayerController.fullscreen = YES;
self.moviePlayerController.scalingMode = MPMovieScalingModeAspectFit;
self.moviePlayerController.controlStyle = MPMovieControlStyleNone;
self.moviePlayerController.movieSourceType = MPMovieSourceTypeFile;
self.moviePlayerController.useApplicationAudioSession = NO;
[self.moviePlayerController.view setFrame: self.view.bounds];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackComplete:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.moviePlayerController];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlaybackStateChanged:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:self.moviePlayerController];
[self.view addSubview:self.moviePlayerController.view];
[self.moviePlayerController prepareToPlay];
[self.moviePlayerController play];
}
Like #Till mentioned:
When I change the MoviePlayerController property to useApplicationAudioSession=TRUE, it fixes my problem. Audio Playback is silent.
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.