複数のサウンド ファイルを再生する必要があります。次のコードがあります。
私.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
しかし、このコードは機能しません。再生される音楽ファイルは 1 つだけです。他のファイルはありません。
また、例があります:
Music1 の再生。
Music2 ボタンを押します -> Music1 終了、Music2 開始。
コードをどのように変更する必要がありますか?