我使用的是AVAudioPlayer框架,并且我有几个声音可以一次播放一个。当一个声音播放完后,我希望应用程序做一些事情。我试图使用audioPlayerDidFinishPlaying在第一个声音的末尾执行操作,但我不能对第二个声音使用它,因为我得到了一个重新定义错误。是否可以使用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];
}
}
发布于 2009-07-11 03:18:22
当一个声音播放完后,我希望应用程序做一些事情。
然后将您自己设置为代理并响应audioPlayerDidFinishPlaying:successfully:
。
在您展示的代码片段中,您已经完成了步骤2,但没有完成步骤1:您没有将自己设置为代理。
在第一个声音…的末尾,我尝试使用applicationDidFinishLaunching
来执行操作
是脑残吗?这个方法与播放声音没有任何关系。
…,但我不能将它用于第二个声音,因为我得到了一个重新定义错误。
哈?您是否实现了该方法两次或什么,而不是仅仅比较方法体中的player对象?
如果您显示得到的确切错误消息,将会有所帮助。
发布于 2017-09-12 10:45:09
Swift 3:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("sound file finished")
}
https://stackoverflow.com/questions/1111691
复制相似问题