2015-03-11 16 views

Trả lời

18

Cách đơn giản nhất là để nhập khẩu các khuôn khổ AudioToolbox như vậy #import <AudioToolbox/AudioToolbox.h> sau đó tất cả các bạn cần làm là:

NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Beep" ofType:@"mp3"]; 
SystemSoundID soundID; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundPath], &soundID); 
AudioServicesPlaySystemSound(soundID); 

này là tốt nhất cho âm thanh thực sự ngắn như tiếng bíp vv bởi vì bạn sẽ không có nhiều quyền kiểm soát có vẻ như bạn sẽ thích với AVAudioPlayer.

+1

Cảm ơn. Dường như đối với âm thanh ngắn, đây là phương pháp tốt nhất. – Kyle

+0

Câu trả lời rất hay nhờ :-) – Josef

+1

mp3 ngắt các âm thanh khác và không thể phát với người khác. Bạn có thể cần caf thay thế. – durazno

10

Sử dụng AVAudio - nhiều mã rằng việc sử dụng các AudioToolbox nhưng nó cũng là linh hoạt hơn (nếu bạn cần nó trong tương lai)

0.

#import <AVFoundation/AVFoundation.h> 

1.

//conform to delegate and make a property 
@interface ViewController() <AVAudioPlayerDelegate> 
@property (nonatomic, strong) AVAudioPlayer *audioplayer; //the player 
@end 

2.

//have a lazy property for the player! where you also tell it to load the sound 
#define YourSound @"sound.caf" 
- (AVAudioPlayer *)audioplayer { 
    if(!_audioplayer) { 
     NSURL *audioURL = [[NSBundle mainBundle] URLForResource:YourSound.stringByDeletingPathExtension withExtension:YourSound.pathExtension]; 
     NSData *audioData = [NSData dataWithContentsOfURL:audioURL]; 
     NSError *error = nil; 
     // assing the audioplayer to a property so ARC won't release it immediately 
     _audioplayer = [[AVAudioPlayer alloc] initWithData:audioData error:&error]; 
     _audioplayer.delegate = self; 
    } 
    return _audioplayer; 
} 

3.

//play 
- (void)action { 
    [self.audioplayer play]; 
} 
+0

Cảm ơn, nó hoạt động cho tôi. Nhưng đối với âm thanh ngắn, tôi sẽ thử các chức năng C. – Kyle

+0

cảm ơn nó đã làm việc cho tôi – BoSoud

2
#Import Avfoundation.Framework 

AVAudioPlayer *_audioPlayer; //Declare Globally 

Nsstring *path =[Nsstring stringwithformat:@"%@/Beep.mp3",[[Nsbundle mainBundle] resourcePath]];   //Give Your Local Path 

Nsurl *soundUrl= [Nsurl FileUrlWithPath:path]; 

_audioPlayer=[[AvAudioPlayer alloc] initwithContents ofurl:soundUrl error:nil]; 

_audioPlayer.volume=1.0; //Give Volume 

_audioPlayer.numberOfLoops=loop; //Give number of loop for repeating sound 

_audioPlayer.enableRate = Yes; 

_audioPlayer.rate=2.0f; //Give for fast playing sound. default value is 1.0f; 

[_audioPlayer Play]; 
Các vấn đề liên quan