Android包含了一个MediaPlayer类,这个类可以用来播放和控制音频和视频。现在我们使用音频功能。MediaPlayer类可用于控制播放的音频/视频文件和流
最简单的MediaPlayer示例是能否与应用程序一起打包的音频文件,也就是音频文件放在原始资源里面。所以,我们在项目的res文件夹下新建一个文件,叫raw,并加入音频文件。
1.启动媒体播放器
位音频文件创建MeidaPlayer非常简单,可以使用静态方法create实例化一个MediaPlayer对象,传入作为上下文的this(活动将源自它)以及音频文件生成的ziyuanID。
MediaPlayer mediaPlayer=MediaPlayer.create(this.R.raw.androidMp3);
当然,也可以用构造方法实例化一个MediaPlayer对象:MediaPlayer mediaPlayer=new MediaPlayer();
之后就可以用mediaPlayer.start();来播放文件了。
2.控制播放
MediaPlayer类有多个嵌套的类,他们是监听MedaiPlayer所发送事件的借口。这些事件与状态变化有关。例如,MediaPlayer将对实现OnCompletionListener并通过setOnCompletionListener注册的类调用onCompletion方法,该操作将在音频文件正在播放时执行。下面是一个完整的示例,该活动将无限次的重复,通过使用OnCompletionLitener播放相同的音频文件。在onStart方法中初始化MediaPlayer对象并开始播放;在onStop方法中停止播放和释放资源。
package com.example.musicdemo;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity implements OnCompletionListener{
MediaPlayer mediaPlay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
mediaPlay=MediaPlayer.create(this,R.raw.android);
mediaPlay.setOnCompletionListener(this);
mediaPlay.start();
}
@Override
protected void onStop() {
super.onStop();
mediaPlay.stop();
mediaPlay.release();
}
public void onCompletion(MediaPlayer mp) {
mediaPlay.start();
}
}
当然,这可以在没有OnCompletionListener的情况下完成,只需简单地通过使用setLooping(true)方法将MediaPlayer设置为循环播放。
MediaPlayer状态图
回放控制音频/视频文件和流的管理是作为一个状态机。下面的图显示了生命周期和一个MediaPlayer对象由支持回放控制操作。椭圆表示状态可能驻留在一个MediaPlayer对象。弧线代表回放控制操作,驱动对象状态转换。有两种类型的弧线。用一个弧线箭头代表同步方法调用头,而那些有双箭头代表异步方法调用负责人。
原文:http://stackoverflow.com/questions/6748996/how-to-set-custom-tick-marks-in-core-plot-to-icons
Axis label 可以使用任何 CPTLayer(CALayer 子类)作为标签。用UIImage 作为 CPTLayer 的背景层即可定制轴标签。有许多Core Plot 的使用定制轴标签的例子,虽然他们用的是文本标签。
有两种方法定制图形类的轴标签:
1、 graph的labeling policy设置为CPTAxisLabelingPolicyNone。创建NSSet,放入所有 AxisLabel,然后将坐标轴的 axisLabels 属性设置为 NSSet。如果用这种方法,你需要提供major/minor tick的location。
2、labeling policy 设置为其他策略,以产生 major/minor tick。然后实现axis:shouldUpdateAxisLabelsAtLocations:委托方法。在方法中,在指定的location创建新的label 然后返回 No 以忽略默认的标签。
Jul 19 '11 at 22:46
Eric Skroch
根据 Eric 的说法,我编写了一些代码,以供参考:
if (yAxisIcons) {
int custonLabelsCount = [self.yAxisIcons count];
NSMutableArray *customLabels =[NSMutableArray arrayWithCapacity:custonLabelsCount];
for (NSUInteger i = 0; i <custonLabelsCount; i++)
{
NSNumber*tickLocation = [NSNumber numberWithInt:i];
NSString *file =[yAxisIcons objectAtIndex:i];
UIImage *icon =[UIImage imageNamed:file];
CPImageLayer*layer; // My custom CPLayer subclass - see code below
CGFloatnativeHeight = 1;
CGFloatnativeWidth = 1;
if (icon) {
layer = [[CPImageLayer alloc] initWithImage:icon];
nativeWidth = 20;//CGImageGetWidth(icon.CGImage);
nativeHeight = 20;//CGImageGetHeight(icon.CGImage);
//layer.contents = (id)icon.CGImage;
if (nativeWidth > biggestCustomIconWidth) {
biggestCustomIconWidth = nativeWidth;
}
}else{
layer= [[CPImageLayer alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
}
CGRect startFrame = CGRectMake(0.0, 0.0,nativeWidth, nativeHeight);
layer.frame= startFrame;
layer.backgroundColor = [UIColor clearColor].CGColor;
CPAxisLabel *newLabel = [[CPAxisLabel alloc]initWithContentLayer:layer];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = x.labelOffset +x.majorTickLength; [customLabels addObject:newLabel];
[newLabel release];
[layer release];
}
y.axisLabels = [NSSetsetWithArray:customLabels];
}
CPImageLayer.h
#import "CPLayer.h"
@interface CPImageLayer : CPLayer {
UIImage*_image;
}
-(id)initWithImage:(UIImage *)image; @end
CPImageLayer.m
#import "CPImageLayer.h" #import "CPLayer.h"
@implementation CPImageLayer
-(void)dealloc{
[_imagerelease];
[super dealloc];
}
-(id)initWithImage:(UIImage *)image{
CGRect f =CGRectMake(0, 0, image.size.width, image.size.height);
if (self =[super initWithFrame:f]) {
_image = [imageretain];
}
return self;
}
-(void)drawInContext:(CGContextRef)ctx{
CGContextDrawImage(ctx, self.bounds, _image.CGImage);
}
@end
Jul 22 '11 at 14:01
Lukasz
http://www.cocoachina.com/bbs/job.php?action=download&aid=26207
自从 Tweetie 大获成功以后,下拉刷新几乎成了所有 App 的内容更新操作方式。如果你不想落入俗套,可以看看下面这段 CocoaChina 会员 “diyago” 分享的上提刷新代码。
下面是.h文件的代码
//
// EGORefreshTableHeaderView.h
// Demo
//
// Created by Devin Doty on 10/14/09October14.
// Copyright 2009 enormego. All rights reserved.
//
//修改人:禚来强 iphone开发qq群:79190809 邮箱:zhuolaiqiang@gmail.com
//原文地址:http://blog.csdn.net/diyagoanyhacker/archive/2011/05/24/6441805.aspx
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
typedef enum{
EGOOPullRefreshPulling = 0,
EGOOPullRefreshNormal,
EGOOPullRefreshLoading,
} EGOPullRefreshState;
@protocol EGORefreshTableHeaderDelegate;
@interface EGORefreshTableHeaderView : UIView {
id _delegate;
EGOPullRefreshState _state;
UILabel *_lastUpdatedLabel;
UILabel *_statusLabel;
CALayer *_arrowImage;
UIActivityIndicatorView *_activityView;
}
@property(nonatomic,assign) id <EGORefreshTableHeaderDelegate> delegate;
- (void)refreshLastUpdatedDate;
- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView;
- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView;
- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView;
@end
@protocol EGORefreshTableHeaderDelegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view;
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view;
@optional
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view;
@end
下面是.m文件的代码
//
// EGORefreshTableHeaderView.m
// Demo
//
//修改人:禚来强 iphone开发qq群:79190809 邮箱:zhuolaiqiang@gmail.com
//
#define RefreshViewHight 65.0f
#import "EGORefreshTableHeaderView.h"
#define TEXT_COLOR [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f
@interface EGORefreshTableHeaderView (Private)
- (void)setState:(EGOPullRefreshState)aState;
@end
@implementation EGORefreshTableHeaderView
@synthesize delegate=_delegate;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame: frame];
if (self) {
self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, RefreshViewHight - 30.0f, self.frame.size.width, 20.0f)];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
label.font = [UIFont systemFontOfSize:12.0f];
label.textColor = TEXT_COLOR;
label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
label.shadowOffset = CGSizeMake(0.0f, 1.0f);
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
[self addSubview:label];
_lastUpdatedLabel=label;
[label release];
label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, RefreshViewHight - 48.0f, self.frame.size.width, 20.0f)];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
label.font = [UIFont boldSystemFontOfSize:13.0f];
label.textColor = TEXT_COLOR;
label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
label.shadowOffset = CGSizeMake(0.0f, 1.0f);
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
[self addSubview:label];
_statusLabel=label;
[label release];
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(25.0f, RefreshViewHight - RefreshViewHight, 30.0f, 55.0f);
layer.contentsGravity = kCAGravityResizeAspect;
layer.contents = (id)[UIImage imageNamed:@"blueArrow.png"].CGImage;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
layer.contentsScale = [[UIScreen mainScreen] scale];
}
#endif
[[self layer] addSublayer:layer];
_arrowImage=layer;
UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
view.frame = CGRectMake(25.0f, RefreshViewHight - 38.0f, 20.0f, 20.0f);
[self addSubview:view];
_activityView = view;
[view release];
[self setState:EGOOPullRefreshNormal];
}
return self;
}
//
// EGORefreshTableHeaderView.h
// Demo
//
// Created by Devin Doty on 10/14/09October14.
// Copyright 2009 enormego. All rights reserved.
//
//修改人:禚来强 iphone开发qq群:79190809 邮箱:zhuolaiqiang@gmail.com
//原文地址:http://blog.csdn.net/diyagoanyhacker/archive/2011/05/24/6441805.aspx
#pragma mark -
#pragma mark Setters
- (void)refreshLastUpdatedDate {
if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceLastUpdated:)]) {
NSDate *date = [_delegate egoRefreshTableHeaderDataSourceLastUpdated:self];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setAMSymbol:@"上午"];
[formatter setPMSymbol:@"下午"];
[formatter setDateFormat:@"yyyy/MM/dd hh:mm:a"];
_lastUpdatedLabel.text = [NSString stringWithFormat:@"最后更新: %@", [formatter stringFromDate:date]];
[[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"EGORefreshTableView_LastRefresh"];
[[NSUserDefaults standardUserDefaults] synchronize];
[formatter release];
} else {
_lastUpdatedLabel.text = nil;
}
}
- (void)setState:(EGOPullRefreshState)aState{
switch (aState) {
case EGOOPullRefreshPulling:
_statusLabel.text = NSLocalizedString(@"松开即可更新...", @"松开即可更新...");
[CATransaction begin];
[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
_arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
[CATransaction commit];
break;
case EGOOPullRefreshNormal:
if (_state == EGOOPullRefreshPulling) {
[CATransaction begin];
[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
_arrowImage.transform = CATransform3DIdentity;
[CATransaction commit];
}
_statusLabel.text = NSLocalizedString(@"上拉即可更新...", @"上拉即可更新...");
[_activityView stopAnimating];
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
_arrowImage.hidden = NO;
_arrowImage.transform = CATransform3DIdentity;
[CATransaction commit];
[self refreshLastUpdatedDate];
break;
case EGOOPullRefreshLoading:
_statusLabel.text = NSLocalizedString(@"加载中...", @"加载中...");
[_activityView startAnimating];
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
_arrowImage.hidden = YES;
[CATransaction commit];
break;
default:
break;
}
_state = aState;
}
#pragma mark -
#pragma mark ScrollView Methods
//手指屏幕上不断拖动调用此方法
- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView {
if (_state == EGOOPullRefreshLoading) {
CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
offset = MIN(offset, 60);
scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0f, RefreshViewHight, 0.0f);
} else if (scrollView.isDragging) {
BOOL _loading = NO;
if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
_loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
}
if (_state == EGOOPullRefreshPulling && scrollView.contentOffset.y + (scrollView.frame.size.height) < scrollView.contentSize.height + RefreshViewHight && scrollView.contentOffset.y > 0.0f && !_loading) {
[self setState:EGOOPullRefreshNormal];
} else if (_state == EGOOPullRefreshNormal && scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height + RefreshViewHight && !_loading) {
[self setState:EGOOPullRefreshPulling];
}
if (scrollView.contentInset.bottom != 0) {
scrollView.contentInset = UIEdgeInsetsZero;
}
}
}
//当用户停止拖动,并且手指从屏幕中拿开的的时候调用此方法
- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {
BOOL _loading = NO;
if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
_loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
}
if (scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height + RefreshViewHight && !_loading) {
if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDidTriggerRefresh:)]) {
[_delegate egoRefreshTableHeaderDidTriggerRefresh:self];
}
[self setState:EGOOPullRefreshLoading];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.2];
scrollView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, RefreshViewHight, 0.0f);
[UIView commitAnimations];
}
}
//当开发者页面页面刷新完毕调用此方法,[delegate egoRefreshScrollViewDataSourceDidFinishedLoading: scrollView];
- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.3];
[scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
[UIView commitAnimations];
[self setState:EGOOPullRefreshNormal];
}
#pragma mark -
#pragma mark Dealloc
- (void)dealloc {
_delegate=nil;
_activityView = nil;
_statusLabel = nil;
_arrowImage = nil;
_lastUpdatedLabel = nil;
[super dealloc];
}
@end
下面是调用类的代码
//
// RootViewController.m
// TableViewPull
//
// Created by Devin Doty on 10/16/09October16.
// Copyright enormego 2009. All rights reserved.
//
//修改:禚来强 email:zhuolaiqiang@gmail.com
#import "RootViewController.h"
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView reloadData];
//self.tableView.contentInset = UIEdgeInsetsMake(200, 0, 320, 480);
if (_refreshHeaderView == nil) {
EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame: CGRectMake(0.0f, self.tableView.contentSize.height, 320, 650)];
NSLog(@"%@", NSStringFromCGRect( view.frame ));
view.delegate = self;
[self.tableView addSubview:view];
_refreshHeaderView = view;
[view release];
}
// update the last update date
[_refreshHeaderView refreshLastUpdatedDate];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [NSString stringWithFormat:@"Section %i", section];
}
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
- (void)reloadTableViewDataSource{
// should be calling your tableviews data source model to reload
// put here just for demo
_reloading = YES;
}
- (void)doneLoadingTableViewData{
// model should call this when its done loading
_reloading = NO;
[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}
#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
[self reloadTableViewDataSource];
[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:4.0];
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
return _reloading; // should return if data source model is reloading
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
return [NSDate date]; // should return date data source was last changed
}
#pragma mark -
#pragma mark Memory Management
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
_refreshHeaderView=nil;
}
- (void)dealloc {
_refreshHeaderView = nil;
[super dealloc];
}
@end
附件下载: 上拉刷新.zip (97 K)