【发布时间】:2014-04-16 17:33:09
【问题描述】:
【问题讨论】:
-
想要在点击按钮时播放声音吗?
-
如果你看一下代码:图像是以编程方式拍摄的......不需要点击按钮:)
-
好的,这没问题,你想在这个过程中播放声音吗?
-
好的,给我一分钟;)
【问题讨论】:
有两种方法可以做到这一点:
1) 使用AVAudioPlayer
在您的myPic.m 中添加:
//at the top
#import <AudioToolbox/AudioToolbox.h>
#import <MediaPlayer/MediaPlayer.h>
@implementation myPic {
AVAudioPlayer *mySound;
}
//then use this function where ever you want to play sound
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"mySound" ofType: @"mp3"]; //wav, aiff, ogg, ext
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
loopUno = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
loopUno.numberOfLoops = 0; // here loop setup infinite is -1
[mySound play];
2) 我更喜欢,没有循环但更稳定的是SystemSoundID soundID
//at the top
#import <AudioToolbox/AudioToolbox.h>
#import <MediaPlayer/MediaPlayer.h>
@implementation myPic {
SystemSoundID soundID;
}
//then use this function where ever you want to play sound
AudioServicesDisposeSystemSoundID(soundID);
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"mySound" ,CFSTR ("mp3") , NULL); //wav, aiff, ogg, ext
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
覆盖扬声器:
- (void)viewDidLoad {
[super viewDidLoad];
AVAudioSession* session = [AVAudioSession sharedInstance];
BOOL success;
NSError* error;
success = [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
success = [session setActive:YES error:&error];
}
或者,如果您在应用中使用更多音频,请在 AppDelegate.m 下的 application didFinishLaunchingWithOptions: 下添加函数并将您的委托导入您需要的地方
希望对您有所帮助;)
【讨论】:
【讨论】: