我已经执行了以下代码,但声音不起作用。在 .h 中
#import <AVFoundation/AVAudioPlayer.h>
#import <AVFoundation/AVFoundation.h>
在 .m
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl];
[player play];
但是我听不到任何声音。实际上我想管理按钮点击声音以及音量按钮,所以我正在使用这种方法。
你设置了音量吗?
[player setVolume:1.0];
播放短声音的另一种方法是 AudioServicesCreateSystemSoundID
.
请参阅链接 在iOS中播放短声音
尝试:
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];
这对我来说非常有效。
将 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);
}