我已执行以下代码,但声音无效。 在.h
#import <AVFoundation/AVAudioPlayer.h>
#import <AVFoundation/AVFoundation.h>
in .m
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl];
[player play];
但是我听不到任何声音。实际上我想管理按钮点击声音和音量按钮,所以我使用这种方法。
答案 0 :(得分:1)
你设定了音量吗?
[player setVolume:1.0];
播放短音的另一种方法是AudioServicesCreateSystemSoundID
。
答案 1 :(得分:1)
尝试:
self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:(__bridge NSURL *)(soundUrl) error:NULL];
self.theAudio.volume = 1.0;
self.theAudio.delegate = self;
[self.theAudio prepareToPlay];
[self.theaudio play];
答案 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);
}