2012-09-03 81 views
1

我正在研究一個小型的AppleScript程序,它可以讓你輸入一行文本和一個數字,而OS X中的文本到語音功能會大聲說出來,由您輸入的數字控制的混響。 (研究我的代碼以獲取詳細信息。)AppleScript:從文件中讀取問題

除了一件事情之外,一切正常。我正在嘗試將計算機所說的內容寫入文本文件,然後將該文本文件加載到您所寫的文本字段中。

寫部分工作得很好,它正在創建一個文本文件,並把我所說的電腦說在那裏。問題在於閱讀。

因爲它是現在,讀部分看起來是這樣的:

try 
    open for access prevSFile 
    set defToSay to (read prevSFile) 
end 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" 

回答

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命令路徑的正確路徑。請注意,您不需要每次都讀取並觸摸文件。只要在重定向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