【发布时间】:2010-11-18 14:36:40
【问题描述】:
我正在开发一个应用程序,它使用一些硬件传感器在屏幕上提供数据,有一个随数字更新的标签。我想在数字超过 100 时播放声音。例如,假设它正在读取数字,然后它突然找到了一个好位置(或其他什么),然后我想要播放声音或点亮灯光。我是一个绝对的初学者,如果答案对一个绝对的初学者来说很容易理解,那就太好了。
【问题讨论】:
标签: iphone objective-c audio
我正在开发一个应用程序,它使用一些硬件传感器在屏幕上提供数据,有一个随数字更新的标签。我想在数字超过 100 时播放声音。例如,假设它正在读取数字,然后它突然找到了一个好位置(或其他什么),然后我想要播放声音或点亮灯光。我是一个绝对的初学者,如果答案对一个绝对的初学者来说很容易理解,那就太好了。
【问题讨论】:
标签: iphone objective-c audio
我正在使用系统 AudioToolbox.framework 在我的简单游戏中播放声音。我将此静态函数添加到通用 MyGame 类中:
+ (SystemSoundID) createSoundID: (NSString*)name
{
NSString *path = [NSString stringWithFormat: @"%@/%@",
[[NSBundle mainBundle] resourcePath], name];
NSURL* filePath = [NSURL fileURLWithPath: path isDirectory: NO];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
return soundID;
}
我将“Morse.aiff”文件添加到项目资源中,并在(任何)类初始化中使用以下内容对其进行了初始化:
self.mySound = [MyGame createSoundID: @"Morse.aiff"];
然后我用这个电话播放了声音:
AudioServicesPlaySystemSound(mySound);
另外,别忘了导入 AudioServices.h 文件。
这个音频工具箱也可以播放不同的声音格式。
【讨论】:
h
#import <AVFoundation/AVFoundation.h>
@interface CMAVSound : NSObject {
AVAudioPlayer *audioPlayer;
}
- (id)initWithPath:(NSString*)fileNameWithExctension;
- (void)play;
@end
米
#import "CMAVSound.h"
@implementation CMAVSound
-(void)dealloc {
[audioPlayer release];
}
- (id)initWithPath:(NSString*)fileNameWithExctension {
if ((self = [super init])) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], fileNameWithExctension]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (audioPlayer == nil) {
NSLog(@"%@", [error description]);
}
}
return self;
}
- (void)play {
[audioPlayer play];
}
@end
【讨论】:
查看AVAudioPlayer 类的文档。它允许您播放声音剪辑。如果您在实现时遇到问题,请向我们展示一些代码。
【讨论】:
如果声音长达 5 秒并且不需要立体声输出,我建议您使用系统声音来执行此操作。这是比任何其他解决方案都简单且更好的解决方案。 Apple 示例代码以名称 SysSound 提供
编辑1 或者也许教程可以帮助你更多 http://howtomakeiphoneapps.com/2009/08/how-to-play-a-short-sound-in-iphone-code/
【讨论】:
在这里你可以找到 AudioServicesPlaySystemSound 的列表
【讨论】: