Một chương trình mà không có nhạc hay âm thanh vào thì quả thật chương trình rất nhàm chán và buồn tẻ.

Sau đây, tôi giới thiệu cho các bạn cách viết lệnh để chương trình chạy có tiếng động để tránh chương trình quá nhàm chán.

Đầu tiên chúng ta phải thêm 2 thư viện (framework) về âm thanh của Xcode vào chương trình để chạy chương trình. Các bạn vào phần thông tin của chương trình. Chọn tab Build Phase sau đó vào Link Binary with Library sau đó add 2 framework

Mã:
AudioToolbox/AudioToolbox

AVFoundation/AVFoundation
Sau đó chúng ta tạo một button để chạy file âm thanh và đừng quên add file nhạc mà các bạn cần chạy vào nữa.

Đây là file header (.h)

Mã:
#import <UIKit/UIKit.h>

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>

 

@interface MainMindViewController : UIViewController<AVAudioPlayerDelegate>{

    SystemSoundID burpSoundID;

    AVAudioPlayer *player;

}

 

- (IBAction)actPlayingSound:(id)sender;

@end
Còn đây là file main (.m):

Mã:
#import “MainMindViewController.h”

 

@interface MainMindViewController ()

 

@end

 

@implementation MainMindViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@”sboom” ofType:@”wav”]]), &burpSoundID);

AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@”sboom” ofType:@”wav”]]), &burpSoundID);

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]

pathForResource:@”MoiHongXaoXuyen”

ofType:@”mp3″]];

NSError *error;

player = [[AVAudioPlayer alloc]

initWithContentsOfURL:url

error:&error];

if (error)

{

NSLog(@”Error in audioPlayer: %@”,

[error localizedDescription]);

} else {

//audioPlayer.delegate = self;

[player prepareToPlay];

}

player.numberOfLoops = -1;

 

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

}

 

- (IBAction)actPlayingSound:(id)sender {

    AudioServicesPlaySystemSound(burpSoundID);

}

@end
Thế là xong, giờ thì click vào button là nghe tiếng ngay.