我在从主视图控制器推出的按钮上播放声音,效果很好。在下一个视图控制器上,我也希望在按下的按钮上播放声音,但我没有听到任何声音。我将两个.h和.m文件设置为相同。我的问题可能是什么?谢谢你的帮助。
我的.m文件:
#import "AboutView.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
@interface AboutView ()
@end
@implementation AboutView
@synthesize support;
@synthesize facebook;
@synthesize kmbdev;
@synthesize back;
@synthesize player2;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNi{
if (self) {
// Custom initialization
}
return self;
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"sound1" ofType: @"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.player2 = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: NULL];
player2.volume = .5;
[player2 prepareToPlay];
}
我的.h文件:
#import "ViewController.h"
#import <MessageUI/MessageUI.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
@class ViewController;
@interface AboutView : UIViewController <MFMailComposeViewControllerDelegate, AVAudioPlayerDelegate>{
AVAudioPlayer *player2;
}
@property (strong, nonatomic) IBOutlet UIButton *back;
- (IBAction)back:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *support;
@property (strong, nonatomic) IBOutlet UIButton *facebook;
@property (strong, nonatomic) IBOutlet UIButton *kmbdev;
- (IBAction)email:(id)sender;
@property (strong, nonatomic) AVAudioPlayer *player2;
@end
我有[player2 play];正如我在主视图控制器上所做的那样准备segue和IBaction。
答案 0 :(得分:1)
在第二个控制器的ViewDidLoad方法中添加此代码:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"sound1" ofType: @"wav"];
if([[NSFileManager defaultManager] fileExistsAtPath:soundFilePath)
{
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
if(fileURL)
{
self.player2 = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
self.player2.delegate = self;
self.player2.volume = 0.5f;
[self.player2. play];
}
}
else {
NSLog(@"File DoesNot Exists");
}