Reputation: 789
I'm trying to get a short audio file (mp3) to play in my app. Here is the code i'm using:
AVAudioPlayer *AudioPlayer;
NSError *error;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"filename"
ofType:@"mp3"]];
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
AudioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
if (error)
{
NSLog(@"Error: %@",
[error localizedDescription]);
}
else
{
[AudioPlayer play];
}
I don't really know what i'm missing, the examples i've followed seem to match what i'm doing.
edit: I should also mention that the code runs without error, there is a try catch around this.
Upvotes: 1
Views: 1516
Reputation: 91911
I had a similar problem due to ARC. Instead of defining the AVAudioPlayer in the same method you are using it, you should should have an instance variable somewhere else, such as the UIViewController. This way ARC doesn't auto release this object and audio can play.
Upvotes: 3
Reputation: 629
I've made some additions and got it work:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface FirstViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *data;
UIButton *playButton_;
}
@property(nonatomic, retain) IBOutlet UIButton *playButton;
-(IBAction)musicPlayButtonClicked:(id)sender;
@end
#import "ViewController.h"
@implementation FirstViewController
@synthesize playButton=playButton_;
- (IBAction)musicPlayButtonClicked:(id)sender {
NSString *name = [[NSString alloc] initWithFormat:@"09 No Money"];
NSString *source = [[NSBundle mainBundle] pathForResource:name ofType:@"mp3"];
if (data) {
[data stop];
data = nil;
}
data=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: source] error:NULL];
data.delegate = self;
[data 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.
}
@end
In Interface Builder I've added a button and connected it with IBOutlet
and musicPlayButtonClicked
IBAction
.
And don't forget to add AVFoundation
framework to your project.
ps I'm really sorry for my english, please, be indulgent.
Upvotes: 1
Reputation: 4561
I had this problem myself, until I found out that the sound was not coming through the speakers (instead - it was redirected to the calls speaker). Try adding this to redirect the sound through the speakers:
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof (doChangeDefaultRoute),
&doChangeDefaultRoute);
Upvotes: 0