如何在iPad上播放系统按钮单击声音



当用户单击在iPad上运行的应用程序中的按钮时,我需要播放一些系统声音。如何在iOS中实现它?

如果你想播放一个短的声音(短于30秒),你可以像这样轻松地做到:

注意:您必须添加音频工具箱框架并将其导入(#import <AudioToolbox/AudioToolbox.h>

SystemSoundID mySSID;
NSString *path = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: path], &mySSID); 
AudioServicesPlaySystemSound(mySSID);

另请注意,该文件可以是:

  • 持续时间不超过 30 秒
  • 线性 PCM 或 IMA4 (IMA/ADPCM) 格式
  • 打包在 .caf、.aif 或 .wav 文件中

你应该使用 AVAudioPlayer。

这里有一个关于使用AVAudioPlayer播放声音的很棒的教程。一个非常简单的用法示例:

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3",dataPath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (audioPlayer == nil)
    NSLog([error description]);
else
    [audioPlayer play];
NSString *path = [[NSBundle mainBundle] pathForResource:@"gorilla 2" ofType:@"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate=self;
[theAudio play];

最新更新