2009-07-10 23 views
16

Estoy usando el marco de AVAudioPlayer, y tengo varios sonidos que se reproducen de a uno por vez. Cuando termina de reproducir un sonido, quiero que la aplicación haga algo. Traté de usar audioPlayerDidFinishPlaying para hacer la acción al final del primer sonido, pero no pude usar eso para el segundo sonido porque recibí un error de redefinición. ¿Puedo usar NSTimeInterval para obtener la duración de un sonido?¿Actúa cuando un sonido ha terminado de reproducirse en AVAudioPlayer?

// 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]; 

} 
} 

Respuesta

24

Cuando un sonido se terminó de juego, quiero que la aplicación pueda hacer algo.

Luego configúrese como el delegado y responda al audioPlayerDidFinishPlaying:successfully:.

En el fragmento de código que mostró, ha realizado el paso 2 pero no el paso 1: no se establece como delegado.

He intentado utilizar applicationDidFinishLaunching para realizar la acción al final del primer sonido ...

pedo cerebro? Ese método no tiene nada que ver con tocar sonidos.

..., pero no pude usar eso para el segundo sonido porque recibí un error de redefinición.

¿Huh? ¿Implementaron el método dos veces o algo en lugar de simplemente comparar el objeto del jugador en el cuerpo del método?

Ayudaría si mostrara el mensaje de error exacto que recibió.

+0

Oh! Sí, tenía la intención de decir audioPlayerDidFinishPlaying, no applicationDidFinishLaunching. Lo siento. Configuré el delegado en uno mismo, y funcionó para el primer sonido. Pero el problema no es que audioPlayerDidFinishPlaying no funcione, el problema es que no sé cómo hacerlo nuevamente para un segundo sonido. Tengo dos sonidos diferentes. – Evelyn

+0

Por cierto, cuando pongo [player setDelegate: self], aparece la advertencia: "class 'ViewController' no implementa el 'AVAudioPlayerDelegate' protocol". ¿Es eso un problema? – Evelyn

+0

Debe establecerse como delegado de ambos sonidos. El sonido se identificará cuando te envíe un mensaje de delegado, para que puedas compararlo con los sonidos que tienes a mano. –

1

Swift 3:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { 
     print("sound file finished") 
    } 
Cuestiones relacionadas