0
我需要播放多个声音文件。我有以下代码:如何播放多个声音?
我.h
类
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
@interface ViewController : UIViewController {
AVAudioPlayer *musicPlayer;
}
- (IBAction)music1:(id)sender;
- (IBAction)music2:(id)sender;
- (IBAction)music3:(id)sender;
- (IBAction)music4:(id)sender;
- (IBAction)music5:(id)sender;
@end
我.m
文件
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)music1:(id)sender {
if(musicPlayer.isPlaying)
{
[musicPlayer pause];
return;
}
if(musicPlayer == nil)
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music1" ofType:@"wav" ]];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
}
[musicPlayer play];
}
- (IBAction) music2:(id)sender {
if(musicPlayer.isPlaying)
{
[musicPlayer pause];
return;
}
if(musicPlayer == nil)
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music2" ofType:@"wav" ]];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
}
[musicPlayer play];
}
- (IBAction) music3:(id)sender {
if(musicPlayer.isPlaying)
{
[musicPlayer pause];
return;
}
if(musicPlayer == nil)
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music3" ofType:@"wav" ]];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
}
[musicPlayer play];
}
- (IBAction) music4:(id)sender {
if(musicPlayer.isPlaying)
{
[musicPlayer pause];
return;
}
if(musicPlayer == nil)
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music4" ofType:@"wav" ]];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
}
[musicPlayer play];
}
- (IBAction) music5:(id)sender {
if(musicPlayer.isPlaying)
{
[musicPlayer pause];
return;
}
if(musicPlayer == nil)
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music5" ofType:@"wav" ]];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
}
[musicPlayer play];
}
@end
但是这个代码不工作:只有一个音乐文件播放。其他文件不是。
此外,还有一个示例:
Music1正在播放。 我按下Music2按钮 - > Music1结束,Music2开始。
我该如何编写代码?
太感谢你了..
然后你最终创造25个音频播放器。我相信你的意思是“你需要五个'AVAudioPlayer's:每个声音一个。” – 2013-02-16 16:54:59
非常感谢你..我错过了评论:) 我的问题的第二个答案是什么? 另外,还有一个例子: Music1正在播放。我按下Music2按钮 - > Music1结束,Music2开始。 如何编写代码? – Axapta 2013-02-16 17:31:16
寻找我的更新答案。这不是最好的解决方案,但它应该工作 – 2013-02-16 17:53:09