Ios4 如何在按下按钮时播放MP3?
有人能给我一个例子代码,告诉我如何用按键播放声音吗Ios4 如何在按下按钮时播放MP3?,ios4,uibutton,mp3,avaudioplayer,iphone,Ios4,Uibutton,Mp3,Avaudioplayer,Iphone,有人能给我一个例子代码,告诉我如何用按键播放声音吗 我想使用AVAudioPlayer播放MP3文件,类似的内容应该会让您开始。将其添加到视图控制器,然后将按钮连接到interface builder中的playAudio操作 在你的头上 #import <AVFoundation/AVFoundation.h> @interface ClassName { ... AVAudioPlayer *audioPlayer; } @property (nonatomic
我想使用AVAudioPlayer播放MP3文件,类似的内容应该会让您开始。将其添加到视图控制器,然后将按钮连接到interface builder中的playAudio操作 在你的头上
#import <AVFoundation/AVFoundation.h>
@interface ClassName {
...
AVAudioPlayer *audioPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
- (IBAction) playAudio;
//ViewController.h,写下面的代码
@界面ViewController:UIViewController
//将属性分配给玩家
@属性(非原子,保留)AVAudioPlayer*玩家;
//然后在ViewDidLoad方法中写入ViewController.m文件
N错误*声音错误;
NSString*path=[[NSBundle mainBundle]pathForResource:@“soundFileName”的类型:@“mp3”];/。mp3播放器文件
NSURL*文件=[[NSURL alloc]initFileURLWithPath:path]//路径
_player=[[AVAudioPlayer alloc]initWithContentsOfURL:文件错误:&soundError]//玩家对象
如果(_player==nil)
{
NSLog(@“播放器因%@”而为空,soundError);
}
其他的
{
[玩家玩];
_播放器。音量=1.0;
[_playersetdelegate:self];
}
//对于停止播放器,您可以使用
//[玩家停止]//要停止此行时,请取消对其注释。
请参见[如何在iPhone上以编程方式播放MP3?]()。
@synthesize audioPlayer;
- (IBAction) playAudio {
NSURL *url = [[NSBundle mainBundle] URLForResource:@"audio" withExtension: @"m4a"];
if (!url){NSLog(@"file not found"); return;}
NSError *error;
self.audioPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error] autorelease];
[audioPlayer play]
}
//ViewController.h ,write below code
@interface ViewController : UIViewController<AVAudioRecorderDelegate,AVAudioPlayerDelegate>
//assign property to player
@property(nonatomic,retain) AVAudioPlayer *player;
//then write in ViewController.m file in ViewDidLoad Method
NSError *soundError;
NSString *path=[[NSBundle mainBundle]pathForResource:@"soundFileName" ofType:@"mp3"]; //.mp3 file for player
NSURL *file=[[NSURL alloc]initFileURLWithPath:path]; //path
_player=[[AVAudioPlayer alloc]initWithContentsOfURL:file error:&soundError]; //player Object
if(_player == nil)
{
NSLog(@"player is empty because of %@",soundError);
}
else
{
[_player play];
_player.volume=1.0;
[_player setDelegate:self];
}
// for stop player you can use
// [_player stop]; //uncomment this line when you wants to stop it.