Try   HackMD

新人資訊

技術-iOS #3-發出聲音吧

這次主要是要學習讓 iPhone 發出聲音,順便演練一下 UI 的排版和 player 的用法,檔案的參照等。首先找到課程所提供的專案骨架 https://github.com/appbrewery/Xylophone-iOS13 其中已經準備好一切的素材,包含七個聲音檔,以七個 View 排成七個縱向 Stack View 的排版,每一個 View 上放一個 Button 設定左右間距的 constraint 構成寬度遞減很像七彩木琴的美麗畫面。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

透過上次學到的拖拉技巧建立程式物件參照,可以七個 Button 全部關聯到同一個 Action,因為這個 keyPressed 接受一個傳入參數 sender,讓函數內部可以完整存取到觸發者元件的屬性,這個程式是抓取觸發者 Label 的 currentTitle,以此為依據去找聲音檔。在觸發同時將 alpha (透明度) 設成半透明,隨即利用 DispatchQueue 系統物件塞入一段程序於 0.2 秒後執行,將透明度恢復原狀,這個功能好強喔。尋找專案檔案系統中的聲音檔則是用 Bundle 物件,使用方法相當友善。最後要播放聲音則採用 AVFoundation 這個系統內建的函式庫。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

執行效果符合預期:

https://youtube.com/shorts/g0F3PM0AMNo

By Newman Chen 2022/7/5