AppleScript:从文件中读取问题

时间:2012-09-03 15:50:27

标签: macos file io applescript

我正在开发一个小AppleScript程序,它可以让你输入一行文字和一个数字,OS X中的文本到语音功能会大声说出来,有一些原始的混响,这是由您输入的数字控制。 (详细研究我的代码。)

一切都很好,除了一件事。我试图将计算机所说的内容写入文本文件,然后将该文本文件加载到您编写应该说的文本字段中。

写入部分工作正常,它正在制作一个文本文件,并将我所做的任何计算机放在那里。问题在于阅读。

就像现在一样,阅读部分如下所示:

try
    open for access prevSFile
    set defToSay to (read prevSFile)
end try

根本没有任何事情发生。如果我尝试删除'try',它会给出错误-500,程序停止。

这是我的代码:

--define variables
set defToSay to ""
set prevSFile to "~/library/prevSFile.txt"

--Fetch info from save file:
try
    open for access prevSFile
    set defToSay to (read prevSFile)
end try

--Display dialoges:
display dialog "What do you want to say?" default answer defToSay
set whatToSay to the text returned of the result
display dialog "How many times do you want to overlay it?" default answer "5"
set overlays to the text returned of the result

--Create/edit save file:
do shell script "cd /"
try
    do shell script "rm " & prevSFile
end try
do shell script "touch " & prevSFile
do shell script "echo " & whatToSay & " >> " & prevSFile

--Say and kill:
repeat overlays times
    tell application "Terminal"
        do script "say " & whatToSay
    end tell
    delay 0.01
end repeat
delay (length of whatToSay) / 5
do shell script "killall Terminal"

1 个答案:

答案 0 :(得分:0)

你的问题就在这里。 AppleScript路径不使用“/”,AppleScript当然不知道“〜”。

"~/library/prevSFile.txt"

这部分代码应该是......

set prevSFile to (path to home folder as text) & "Library:prevSFile.txt"
try
    set defToSay to (read file prevSFile)
end try

现在您已拥有AppleScript的正确路径,您需要修复shell命令的路径。请注意,您不需要每次都使用rm并触摸文件。只需使用“>”重定向echo命令时会覆盖该文件。如果有空格,您还需要使用路径的“引用形式”。

do shell script "echo " & quoted form of whatToSay & " > " & quoted form of POSIX path of prevSFile

但是你在那个剧本中做了很多不必要的事情。这是我编写代码的方式。祝你好运。

property whatToSay : ""
property numberOfTimes : 5

--Display dialoges:
display dialog "What do you want to say?" default answer whatToSay
set whatToSay to the text returned of the result

repeat
    display dialog "How many times do you want to overlay it?" default answer (numberOfTimes as text)
    try
        set numberOfTimes to the (text returned of the result) as number
        exit repeat
    on error
        display dialog "Please enter only numbers!" buttons {"OK"} default button 1
    end try
end repeat

repeat numberOfTimes times
    say whatToSay
end repeat