2012-02-02 156 views
1

我试图在我的应用程序中播放短音频文件(mp3)。下面是我使用的代码:AVAudioPlayer不播放我的MP3

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]; 

    } 

我真的不知道我错过了什么,我已经跟着例子似乎与我在做什么。

编辑:我还应该提到,代码运行没有错误,有一个尝试解决这个问题。

回答

0

我自己也有这个问题,直到我发现声音没有通过扬声器(相反 - 它被重定向到通话扬声器)。尝试添加该通过扬声器声音重定向:

​​
1

我做了一些补充和得到它的工作:在Interface Builder我用IBOutlet添加一个按钮,并将其连接

#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 

musicPlayButtonClickedIBAction

并且不要忘记将AVFoundation框架添加到您的项目中。

ps 我真的对不起我的英文,请放纵。

3

由于ARC,我有类似的问题。你不应该使用与你使用的方法相同的方法来定义AVAudioPlayer,而应该在其他地方有一个实例变量,比如UIViewController。这样ARC不会自动释放这个对象并且音频可以播放。

+0

非常感谢这个提示男人。你保存了一天。和平:) – 2013-09-17 17:12:44