在Objective-C中播放声音之前更改视图

时间:2011-06-20 03:12:00

标签: objective-c view audio wav

我有一个播放两种声音的程序。我希望用户知道正在播放哪种声音,所以我有两个大按钮图像。我有三种不同的视图,我想在它们之间切换 - 一个是两个按钮都是红色(没有播放),另外两个按钮中的一个是绿色(显示哪个正在播放)。

我得到的主要问题是我的声音在视图交换之前播放和完成! (我在播放声音之前使用[window setContentView:firstSound])

更改的视图最终会显示,但只有在播放wavs的方法完成后才会显示。

我正在使用NSSound播放声音文件(它们都是短wav文件,所以我觉得合适)

任何人都知道我做错了什么?或者,如果有另一种方法,我可以做到这一点?谢谢堆!

编辑:我已按照建议进行操作,以便只更改图像(而不是视图),但会出现同样的问题。声音播放完毕后会进行更新。

以下是代码:

-(void)readWavs{

//[window setContentView:firstWav];

[redButton setHidden:YES];

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"fish" ofType:@"wav"];
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
[sound play];
sleep(3); //needed so that the sound will actually play
[sound stop];
[sound release];


//[redButton setHidden:NO];
//[window setContentView:testView];

sleep(2);

//[window setContentView:secondWav];

NSString *resourcePath2 = [[NSBundle mainBundle] pathForResource:@"fish" ofType:@"wav"];
NSSound *sound2 = [[NSSound alloc] initWithContentsOfFile:resourcePath2 byReference:YES];
[sound2 play];
sleep(3);
[sound2 stop];
[sound2 release];

//[window setContentView:firstWav]; [redButton setHidden:YES]; NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"fish" ofType:@"wav"]; NSSound *sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES]; [sound play]; sleep(3); //needed so that the sound will actually play [sound stop]; [sound release]; //[redButton setHidden:NO]; //[window setContentView:testView]; sleep(2); //[window setContentView:secondWav]; NSString *resourcePath2 = [[NSBundle mainBundle] pathForResource:@"fish" ofType:@"wav"]; NSSound *sound2 = [[NSSound alloc] initWithContentsOfFile:resourcePath2 byReference:YES]; [sound2 play]; sleep(3); [sound2 stop]; [sound2 release];

绿色“开启”按钮应在播放声音之前显示,但只有在方法完成后才会显示。

2 个答案:

答案 0 :(得分:2)

我不确定我是否理解正确,但听起来你正试图在播放声音时显示正在播放的声音(通过图像)切换到完全不同的视图?如果是这样,您应该使用imageView.hidden = YES和imageView.hidden = NO来显示基于声音的正确图像。更好的是,您可以使用一个图像视图并根据声音更改图像视图中显示的图像。

答案 1 :(得分:1)

您正在使用sleep()阻止运行循环。在完成当前事件的所有处理之前,不会更新显示,并且在此readWavs方法完成之前不会更新。

如果您想在声音结束后执行某些操作,请为其指定一个委托(可能是启动声音的同一对象)并实施NSSoundDelegate -sound:didFinishPlaying:方法。然后,在readWavs中,只需启动声音并返回 - 您的委托方法将在完成时被调用,并且因为readWavs会立即返回,所以它不会阻止运行循环。