2008-11-13 7 views
5

He escrito un & tarjeta de sonido alegre barata en mi Mac, y reproducir los diferentes sonidos con NSSound así:Cómo desaparecer un objeto NSSound

-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying { 
    BOOL wasPlaying = FALSE; 

    if([nowPlaying isPlaying]) { 
     [nowPlaying stop]; 
     wasPlaying = TRUE; 
    } 

    if(soundEffect != nowPlaying) 
    { 
     [soundEffect play]; 
     nowPlaying = soundEffect; 
    } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) { 
     [nowPlaying play]; 
    } 
} 

En lugar de detenerlo muerto, Me gustaría que se desvaneciera en un par de segundos más o menos.

Respuesta

1

Ésta es la versión final del método:

-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying { 
    BOOL wasPlaying = FALSE; 

    if([nowPlaying isPlaying]) { 
     struct timespec ts; 
     ts.tv_sec = 0; 
     ts.tv_nsec = 25000000; 

     // If the sound effect is the same, fade it out. 
     if(soundEffect == nowPlaying) 
     { 
      for(int i = 1; i < 30; ++i) 
      { 
       [nowPlaying setVolume: (1.0/i)]; 
       nanosleep(&ts, &ts); 
      }   
     } 

     [nowPlaying stop]; 
     [nowPlaying setVolume:1]; 
     wasPlaying = TRUE; 
    } 

    if(soundEffect != nowPlaying) 
    { 
     [soundEffect play]; 
     nowPlaying = soundEffect; 
    } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) { 
     [nowPlaying play]; 
    } 
} 

lo tanto, sólo se desvanece si paso el mismo sonido en (es decir, haga clic en el mismo botón), también, fui por nanosleep en lugar de dormir, ya que tiene una granularidad de 1 segundo.

que luchaban por un tiempo tratando de averiguar por qué no parecía mi retardo de 200 milisegundos para tener algún efecto, pero luego 200 nanosegundos no es realmente tan larga es él :-)

0

¿Algo así como esto? Es probable que desee un descenso más lineal, pero la idea básica es hacer un ciclo y dormir el período de tiempo hasta la próxima actualización.

if([nowPlaying isPlaying]) { 
    for(int i = 1; i < 100; ++i) 
    { 
     [nowPlaying setVolume: (1.0/i)]; 
     Sleep(20); 
    } 
    [nowPlaying stop]; 
    wasPlaying = TRUE; 
} 
+0

Acabo de probar este Chris, la función Sleep puso toda la portátil a dormir, lo que me hizo reír. sleep funciona bien, excepto el parámetro que toma en segundos en lugar de milisegundos. –

+0

¡Maldita llave de cambio errante! –

1

me gustaría utilizar NSTimer para evitar bloquear el hilo principal.

+0

¿Puede explicar cómo usaría exactamente el NSTimer? – Matt

Cuestiones relacionadas