我试着用这个代码示例构建一个测试应用程序。
我定义一个公共类如下所示:
public class iSpeech
{
// Performs synthesis
public async Task<IRandomAccessStream> SynthesizeTextToSpeechAsync(string text)
{
IRandomAccessStream stream = null;
using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
{
VoiceInformation voiceInfo =
(
from voice in SpeechSynthesizer.AllVoices
where voice.Gender == VoiceGender.Male
select voice
).FirstOrDefault() ?? SpeechSynthesizer.DefaultVoice;
synthesizer.Voice = voiceInfo;
stream = await synthesizer.SynthesizeTextToStreamAsync(text);
}
return (stream);
}
// Build audio stream
public async Task SpeakTextAsync(string text, MediaElement mediaElement)
{
IRandomAccessStream stream = await this.SynthesizeTextToSpeechAsync(text);
await mediaElement.PlayStreamAsync(stream, true);
}
}然后,在应用程序主页上,我尝试调用如下:
public async void btnClick(object sender, RoutedEventArgs e)
{
await iSpeech.SpeakTextAsync("test speech", this.uiMediaElement);
}我一直在
“非静态字段、方法或属性需要对象引用.”错误。
有人能告诉我我做错了什么吗?
发布于 2016-07-16 01:52:42
iSpeech是一个类,但是您需要类的一个实例才能使用非静态方法。
把它想象成List<string>。你不能打电话
List<string>.Add("Hello"); 因为List<string>是一个类,就像创建对象的蓝图一样。(您将得到完全相同的错误。)您需要创建该类的一个实例来使用它:
var myList = new List<string>();
myList.Add("Hello");所以对于您的类,iSpeech,如果您声明
var mySpeechThing = new iSpeech();然后mySpeechThing将是一个表示iSpeech实例的变量,然后您可以这样做。
await mySpeechThing.SpeakTextAsync("test speech", this.uiMediaElement);有时,类的方法可以在不修改对象状态的情况下被调用(就像在Add上调用List<string>,通过向其添加一个字符串来改变它的状态)。我们将它们声明为static方法。它们属于类,而不是类的实例。
要做到这一点,您需要在方法声明中添加关键字static,如下所示:
public static async Task SpeakTextAsync(string text, MediaElement mediaElement)然后你就可以用你想要的方式了。
static方法不能访问非静态类属性或方法.虽然有些人可能不同意,但是最好不要使用static方法。它们不是邪恶的,但除非你更熟悉,否则我会向另一个方向倾斜。
发布于 2016-07-16 01:45:30
在方法SpeakTextAsync中缺少“静态”关键字。
public static async Task SpeakTextAsync(string text, MediaElement mediaElement)
{
IRandomAccessStream stream = await this.SynthesizeTextToSpeechAsync(text);
await mediaElement.PlayStreamAsync(stream, true);
}https://stackoverflow.com/questions/38406900
复制相似问题