【发布时间】:2012-05-24 13:34:14
【问题描述】:
当用户单击我在 iPad 上运行的应用程序中的按钮时,我需要播放一些系统声音。如何在 iOS 中实现?
【问题讨论】:
标签: objective-c ios xcode ipad
当用户单击我在 iPad 上运行的应用程序中的按钮时,我需要播放一些系统声音。如何在 iOS 中实现?
【问题讨论】:
标签: objective-c ios xcode ipad
如果你想播放一个短的声音(少于 30 秒),你可以像这样轻松地做到这一点:
注意:您必须添加 AudioToolbox 框架并将其导入 (#import <AudioToolbox/AudioToolbox.h>)
SystemSoundID mySSID;
NSString *path = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: path], &mySSID);
AudioServicesPlaySystemSound(mySSID);
还要注意文件可以是:
【讨论】:
/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.sdk/System/Library/Frameworks/UIKit.framework 该文件名为Tock.aiff。只需将此文件添加到您的项目中即可。
你应该使用 AVAudioPlayer。
有一个很棒的教程here 使用 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];
【讨论】: