2009-12-29 21 views
13

¿Cuál es la forma más fácil de reproducir un archivo de música como Mp3 con botón de pausa? muy, muy simple, un botón reproducir y otro botón pausa esa música .. puede escribir ese código!Reproducir archivos MP3 con SDK de iPhone

Respuesta

33

Estos son los códigos para las acciones solicitadas, appSoundPlayer es una propiedad de AVAudioPlayer declarada en el archivo h. También este ejemplo reproduce una canción en la carpeta de recursos.

#pragma mark - 
    #pragma mark *play* 
    - (IBAction) playaction { 

     NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"songname" ofType:@"mp3"]; 
     NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; 
     self.soundFileURL = newURL; 
     [newURL release]; 
     [[AVAudioSession sharedInstance] setDelegate: self]; 
     [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil]; 

    // Registers the audio route change listener callback function 
    AudioSessionAddPropertyListener (
            kAudioSessionProperty_AudioRouteChange, 
            audioRouteChangeListenerCallback, 
            self 
            ); 

    // Activates the audio session. 

    NSError *activationError = nil; 
    [[AVAudioSession sharedInstance] setActive: YES error: &activationError]; 

    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil]; 
    self.appSoundPlayer = newPlayer; 
    [newPlayer release]; 
    [appSoundPlayer prepareToPlay]; 
    [appSoundPlayer setVolume: 1.0]; 
    [appSoundPlayer setDelegate: self]; 
    [appSoundPlayer play]; 


    [stopbutton setEnabled:YES]; 
    [playbutton setEnabled: NO]; 
    playbutton.hidden=YES; 
    pausebutton.hidden =NO; 
}//playbutton touch up inside 

#pragma mark - 
#pragma mark *pause* 
-(IBAction)pauseaction { 
    [appSoundPlayer pause]; 
    pausebutton.hidden = YES; 
    resumebutton.hidden = NO; 

}//pausebutton touch up inside 

#pragma mark - 
#pragma mark *resume* 
-(IBAction)resumeaction{ 
    [appSoundPlayer prepareToPlay]; 
    [appSoundPlayer setVolume:1.0]; 
    [appSoundPlayer setDelegate: self]; 
    [appSoundPlayer play]; 
    playbutton.hidden=YES; 
    resumebutton.hidden =YES; 
    pausebutton.hidden = NO; 

}//resumebutton touch up inside 

#pragma mark - 
#pragma mark *stop* 
-(IBAction)stopaction{ 

    [appSoundPlayer stop]; 
    [playbutton setEnabled:YES]; 
    [stopbutton setEnabled:NO]; 
    playbutton.hidden=NO; 
    resumebutton.hidden =YES; 
    pausebutton.hidden = YES; 

}//stopbutton touch up inside 
+0

muestra el código de este tutorial? – Momi

+1

esos errores son debido a que no los ha declarado en el archivo h. – Nithin

+0

¿Funcionó este código para el NSURL ... reproduciendo el almacenamiento en búfer de audio desde el servidor? –

7

bien here es un buen tutorial disponible.

El tema es

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]]; 

    NSError *error; 
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = -1; 

[audioPlayer play]; 

y cuando se quiere hacer una pausa;

[audioPlayer pause]; 

Espero que esto ayude.

+1

muchas gracias amo a http://stackoverflow.com y por supuesto usted: D – Momi

+0

OK, tengo un problema otra vez. cuando toco el botón Reproducir varias veces, la música suena y sigue ... !! ¿cómo se puede reproducir música 1 vez? y sobre el botón de pausa, ¿quién lo trabaja? lo siento iam amateur: – Momi

25

Para sonidos cortos o cuando el MP3 no juega bien en el código sugerido que siempre puede utilizar:

SystemSoundID soundID; 
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound.mp3", [[NSBundle mainBundle] resourcePath]]]; 

AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID); 
AudioServicesPlaySystemSound (soundID); 

No se olvide de añadir:

#import <AudioToolbox/AudioToolbox.h> 
+0

¡muchas gracias por esto! – rwarner

+1

Gracias, funcionó para mí. Con ARC: AudioServicesCreateSystemSoundID ((__ bridge CFURLRef) url, & soundID); –

0

El código de ejemplo en oalTouch el sitio web para desarrolladores de Apple iOS hace lo que quiere y está listo para ejecutarse.

También muestra cómo probar si otra aplicación (por ejemplo, ipod) ya está reproduciendo un archivo, lo que es útil si desea permitir que los usuarios escuchen su propia música en lugar de la suya.

5

Me temo que la respuesta ya no funciona declaró en iOS 7 y superior. Usted tendrá que utilizar el siguiente código:

en el archivo de cabecera (.h)

el fin de manejar los métodos de delegado como cuando el juego de terminar el audio audioPlayerDidFinishPlaying :, heredar de AVAudioPlayerDelegate.

@property (nonatomic, strong) AVAudioPlayer *player; 

en el archivo de implementación (.m)

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: resourceName 
                  ofType: @"mp3"]; 
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; 

AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL 
                    error: nil]; 
_player = newPlayer; 
[_player prepareToPlay]; 
[_player setDelegate: self]; 
[_player play]; 
1

me gusta código simple y aquí está mi solución: (. Recuerde agregar el botón de interruptor para llegar reproducción de música Diviértete)

#import "ViewController.h" 
#import <AVFoundation/AVFoundation.h> 

@interface ViewController() 
{ 
    NSURL*     bgURL; 
    AVAudioPlayer*   bgPlayer; 
} 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    bgURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mp3"]]; 
    bgPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:bgURL error:nil]; 
} 

#pragma mark AVAudioPlayer 
- (IBAction)toggleMusic:(UISwitch*)sender { 
    NSLog(@"togging music %s", sender.on ? "on" : "off"); 

    if (bgPlayer) { 

     if (sender.on) { 
      [bgPlayer play]; 
     } 
     else { 
      [bgPlayer stop]; 
     } 
    } 
} 
Cuestiones relacionadas