Как воспроизвести MP3, когда нажата кнопка UIB? - PullRequest
0 голосов
/ 26 декабря 2010

Может кто-нибудь дать мне пример кода того, как воспроизводится звук при нажатии кнопки UIB?

Я хотел бы воспроизвести файл MP3 с помощью AVAudioPlayer

Ответы [ 2 ]

1 голос
/ 04 января 2011

что-то вроде этого должно начать вас. Добавьте это в свой контроллер представления, затем подключите кнопку к действию playAudio в построителе интерфейса.

в вашем заголовке .h

#import <AVFoundation/AVFoundation.h>

@interface ClassName {
    ...
    AVAudioPlayer *audioPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;

- (IBAction) playAudio;

в вашем .m

@synthesize audioPlayer;

- (IBAction) playAudio {
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"audio" withExtension: @"m4a"];
    if (!url){NSLog(@"file not found"); return;}
    NSError *error;
    self.audioPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error] autorelease];
    [audioPlayer play]
}
0 голосов
/ 19 мая 2015
//ViewController.h ,write below code
@interface ViewController : UIViewController<AVAudioRecorderDelegate,AVAudioPlayerDelegate>

//assign property to player
 @property(nonatomic,retain) AVAudioPlayer *player;

//then write in ViewController.m file in ViewDidLoad Method

NSError *soundError;
NSString *path=[[NSBundle mainBundle]pathForResource:@"soundFileName" ofType:@"mp3"]; //.mp3 file for player
NSURL *file=[[NSURL alloc]initFileURLWithPath:path]; //path
_player=[[AVAudioPlayer alloc]initWithContentsOfURL:file error:&soundError]; //player Object

if(_player == nil)
{
    NSLog(@"player is empty because of %@",soundError);
}
else
{
    [_player play];
    _player.volume=1.0;
    [_player setDelegate:self];

}

// for stop player you can use 
    // [_player stop]; //uncomment this line when you wants to stop it.
...