2013-10-13 62 views
0

目标: 我试图让按钮被点击时播放声音。这个声音将通过一个叫做“play”的动作来完成。声音在我的资源文件夹中,称为SoftClick.mp3xcode5 - 按下按钮后播放声音不起作用

问题: 在模拟器或实际设备中都没有声音播放。该代码不会给出任何错误。

连接: 需要发出声音的按钮连接到动作播放,并用作模态塞格来显示另一个视图控制器。两个视图控制器都使用相同的.h和.m脚本。

CODE FOR .H 
#import <UIKit/UIKit.h> 
#import<AVFoundation/AVAudioPlayer.h> 


@interface ViewController : UIViewController 

{ 
    AVAudioPlayer *audioPlayer; 

} 

@property (nonatomic, retain) AVAudioPlayer *audioPlayer; 



- (IBAction) play; 




@end 

行动和audioplayer被定义为我认为是必要的(?)

THE CODE FOR .M 
#import "ViewController.h" 
#import<AVFoundation/AVAudioPlayer.h> 
@interface ViewController() 

@end 

@implementation ViewController 

@synthesize audioPlayer; 


-(IBAction)play 

{ 

    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"SoftClick"ofType:@"mp3"]] error:NULL]; 

    [theAudio play]; 

} 

是否有人可以帮我纠正我的编码所以这可能在xcode5工作? 我花了几个小时试图弄清楚为什么这将无法正常工作,像没有segue等尝试的组合我不想窃取别人的代码,并试图建立这个我自己的。

在先进的感谢,

连战

+0

可能重复的[如何在iPad上播放系统按钮点击声音](http://stackoverflow.com/questions/10738551/how-to-play-system-button-click-sound- on-ipad) – Mundi

+0

这不是重复的。 –

回答

0

的问题,因为我假设你正在使用ARC,是你不持有AVAudioPlayer对象。你创建这个对象,调用play,但是它会立即释放并释放。您需要添加self.audioPlayer = theAudio;