AVAudioPlayer でサウンドの再生が終了したらアクションを実行しますか?
-
12-09-2019 - |
質問
私は AVAudioPlayer フレームワークを使用しており、一度に 1 つずつ再生する複数のサウンドがあります。サウンドの再生が終了したら、アプリケーションに何かをさせたいと考えています。audioPlayerDidFinishPlaying を使用して最初のサウンドの終わりにアクションを実行しようとしましたが、再定義エラーが発生したため、2 番目のサウンドにそれを使用できませんでした。NSTimeInterval を使用してサウンドの長さを取得できますか?
// ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface ViewController : UIViewController {
UIButton *begin;
UIWindow *firstTestWindow;
UIWindow *secondTestWindow;
AVAudioPlayer *player;
NSTimeInterval duration;
}
@property (nonatomic, retain) IBOutlet UIButton *begin;
@property (nonatomic, retain) IBOutlet UIWindow *firstTestWindow;
@property (nonatomic, retain) IBOutlet UIWindow *secondTestWindow;
@property (nonatomic, retain) AVAudioPlayer *player;
@property (readonly) NSTimeInterval duration;
- (IBAction)begin:(id)sender;
- (IBAction)doTapScreen:(id)sender;
@end
//ViewController.m
#import "ViewController.h"
@implementation ViewController
@synthesize begin, player, firstTestWindow, secondTestWindow;
//first sound
- (IBAction)begin:(id)sender; {
[firstTestWindow makeKeyAndVisible];
NSString *soundFilePath =
[[NSBundle mainBundle] pathForResource: @"Tone1"
ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
self.player = newPlayer;
[newPlayer release];
[player prepareToPlay];
[self.player play];
}
//If user does not do anything by the end of the sound go to secondWindow
- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player
successfully: (BOOL) flag {
if (flag==YES) {
[secondWindow makeKeyAndVisible];
}
}
//second sound
- (IBAction)doTapScreen:(id)sender {
//When user touches the screen, either play the sound or go to the next window
if (self.player.playing) {
[self.player stop];
[thirdWindow makeKeyAndVisible];
}
else {
NSString *soundFilePath =
[[NSBundle mainBundle] pathForResource: @"Tone2"
ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
self.player = newPlayer;
[newPlayer release];
[player prepareToPlay];
[self.player play];
}
}
解決
サウンドの再生が終了すると、、私は、アプリケーションが何かをしたい。
次に、デリゲートとして自分自身を設定し、audioPlayerDidFinishPlaying:successfully:
に応えます。
コードでは、ステップ2ではなく、ステップ1をやった:あなたは、デリゲートとして自分自身を設定していない
。私は、最初の音の終わり...
でアクションを実行するためにapplicationDidFinishLaunching
を使用しようとしました
脳のおなら?その方法は、私が音を演奏して行うには見ることができます何もしています。
...が、私は再定義エラーを得たので、私は、第二の音のためにそれを使用することができませんでした。
えっ?あなただけのメソッド本体にプレイヤオブジェクトを比較するのではなく、二回法か何かを実装しましたか?
あなたはあなたが得た正確なエラーメッセージを示した場合、それが役立つだろう。
他のヒント
スイフト 3:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("sound file finished")
}
所属していません StackOverflow