我正在尝试在我的iphone应用程序中播放短暂的警报声 我正在使用我发现的这个代码,但它不会播放任何声音。
NSString *toneFilename = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"];
NSURL *toneURLRef = [NSURL fileURLWithPath:toneFilename];
SystemSoundID Sound;
AudioServicesCreateSystemSoundID(
(__bridge CFURLRef) toneURLRef,
&camerSound
);
AudioServicesPlaySystemSound(Sound);
当我尝试制作振动时,它可以工作:
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
Thx
答案 0 :(得分:3)
使用AVFoundationFramework
将AVFoundation.framework
添加到项目中。
#import <AVFoundation/AVFoundation.h>
NSString *toneFilename = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"];
NSURL *toneURLRef = [NSURL fileURLWithPath:toneFilename];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL: toneURLRef error: nil];
player.currentTime = 0;
player.volume = 1.0f;
[player play];
答案 1 :(得分:1)
创建声音时,您没有正确处理Sound
变量。而是使用camerSound
。使用正确的参数调用AudioServicesPlayAlertSound
应该有效。
答案 2 :(得分:1)
这对我来说非常适合。
将AVFoundation和AudioToolBox框架添加到项目中
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
@interface TestViewController : UIViewController
{
SystemSoundID SoundID;
}
@implementation TestViewController
-(void) viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"caf"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &SoundID); //When using ARC, make sure to use __bridge
}
-(void) playSound {
AudioServicesPlaySystemSound(SoundID);
}