Как я могу воспроизвести звук на iPhone с помощью MonoTouch?
-
13-09-2019 - |
Вопрос
Я ищу что-то вроде
PlaySound (uint frequency)
Существует ли оно?
Решение
Из руководства по адресу: http://wiki.monotouch.net/HowTo/Sound/Play_a_Sound_or_Alert
var sound = SystemSound.FromFile (new NSUrl ("File.caf"));
sound.PlaySystemSound ();
Другие советы
Я не знаю насчет mono, но в iPhone SDK создавать и воспроизводить звук не так-то просто.Другие альтернативы - предоставить звук в виде файла и воспроизвести его, или создать массив, представляющий синусоиду, обернуть его аудиооберткой и передать в один из многих звуковых API.
Если mono окажется таким же ограниченным, то выполните поиск stackoverflow.com для системных звуковых служб и AVAudioPlayer в качестве отправных точек.
Вот два способа воспроизведения звукового файла:
SoundEffect.c (на основе Apple)
#import "SoundEffect.h"
@implementation SoundEffect
+ (id)soundEffectWithContentsOfFile:(NSString *)aPath {
if (aPath) {
return [[[SoundEffect alloc] initWithContentsOfFile:aPath] autorelease];
}
return nil;
}
- (id)initWithContentsOfFile:(NSString *)path {
self = [super init];
if (self != nil) {
NSURL *aFileURL = [NSURL fileURLWithPath:path isDirectory:NO];
if (aFileURL != nil) {
SystemSoundID aSoundID;
OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)aFileURL, &aSoundID);
if (error == kAudioServicesNoError) { // success
_soundID = aSoundID;
} else {
NSLog(@"Error %d loading sound at path: %@", error, path);
[self release], self = nil;
}
} else {
NSLog(@"NSURL is nil for path: %@", path);
[self release], self = nil;
}
}
return self;
}
-(void)dealloc {
AudioServicesDisposeSystemSoundID(_soundID);
NSLog(@"Releasing in SoundEffect");
[super dealloc];
// self = nil;
}
-(void)play {
AudioServicesPlaySystemSound(_soundID);
}
-(void)playvibe {
AudioServicesPlayAlertSound(_soundID);
}
+(void)justvibe {
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
}
@end
Звуковой эффект.h:
#import <AudioToolbox/AudioServices.h>
@interface SoundEffect : NSObject {
SystemSoundID _soundID;
}
+ (id)soundEffectWithContentsOfFile:(NSString *)aPath;
- (id)initWithContentsOfFile:(NSString *)path;
- (void)play;
- (void)playvibe;
+ (void)justvibe;
@end
Как это использовать:
// load the sound
gameOverSound = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:@"buzz" ofType:@"caf"]];
// play the sound
[gameOverSound playvibe];
Это полезно, когда вы хотите воспроизводить звук с той же громкостью, что и на регуляторе громкости iPhone, и вам не нужно будет останавливать или приостанавливать звук.
Другой способ - это:
+ (AVAudioPlayer *) newSoundWithName: (NSString *) name;
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: name ofType: @"caf"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
// if the sound is large and you need to preload it:
[newPlayer prepareToPlay];
return (newPlayer);
}
и используйте его (вы можете увидеть все дополнительные функции при использовании AVAudioPlayer).:
timePassingSound = [AVAudioPlayer newSoundWithName:@"ClockTicking"];
[timePassingSound play];
// change the volume
[timePassingSound volume:0.5];
// pause to keep it at the same place in the sound
[timePassingSound pause];
// stop to stop completely, and go to beginning
[timePassingSound stop];
// check to see if sound is still playing
[timePassingSound isPlaying];