我有一張圖片CALayer,當我觸摸時有動畫,效果很好。我現在想要做的也是當你按下相同的圖像時播放聲音剪輯。我發現這很棘手,因爲CALayer來自名爲BounceView的UIView類。我在我的MainViewController上創建了BounceView的一個實例。如果我沒有使用正確的術語,我很抱歉。我是否需要將我的音頻代碼放在我的MainViewController中,然後使用委派允許BounceView在MainViewController上觸發一個方法?任何幫助或方向,不勝感激。CALayers and Audio
MainViewController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
@interface MainViewController : UIViewController <AVAudioPlayerDelegate>
@property (nonatomic, retain) IBOutlet UIView *BounceView;
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
- (IBAction)playAudio:(id)sender;
@end
MainViewController.m
#import "MainViewController.h"
#import "BounceView.h"
@interface MainViewController()
@end
@implementation MainViewController
@synthesize BounceView;
@synthesize audioPlayer;
- (void)viewDidLoad
{
[super viewDidLoad];
//Setup the audio player
NSURL *noSoundFileURL=[NSURL fileURLWithPath:
[[NSBundle mainBundle]
pathForResource:@"InTheMood" ofType:@"mp3"]];
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:noSoundFileURL error:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)loadView
{
NSLog(@"loadView");
// Create a view
CGRect frame = [[UIScreen mainScreen] bounds];
BounceView *v = [[BounceView alloc] initWithFrame:frame];
// Set it as *the* view of this view controller
[self setView:v];
}
- (IBAction)playAudio:(id)sender {
// self.audioPlayer.delegate=self;
[self.audioPlayer play];
}
@end
BounceView.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import "MainViewController.h"
@interface BounceView : UIView
{
CALayer *myLayer;
}
@end
BounceView.m 如果要求我提供這個代碼,但我不知道想要重載代碼。在這裏,我創建了新的圖層打開(alloc init),給它的大小,位置,創建UIImage,獲取底層CGImage &把它放在圖層上,然後使視圖的圖層的子圖層。
再次,任何幫助,非常感謝。
你也想彈一個聲音回彈查看mainVC上的相同我是吧? – Bazinga
當我在BounceView上點擊/觸摸圖層/圖像時,我想播放音符。 – myData
把你的音頻播放器放在啓動你的圖層/圖像的方法中,它應該沒問題,然後在你需要它啓動時停止。 – Bazinga