Mix.install/2関数で、https://hex.pm/ にパブリッシュされていないHexを取り込んでElixirのプログラミングを楽しむ


今来むと言ひしばかりに長月の有明の月を待ちいでつるかな


Advent Calendar 2022 70日目1の記事です。
I'm looking forward to 12/25,2022
私のAdvent Calendar 2022 一覧


はじめに

Elixirを楽しんでいますか

Mix.install/2関数があります。
Mix.install/2関数を使うことで、Mixタスクmix newなどでElixirプロジェクトを作成しなくても、野良の1ファイル.exsでライブラリを使用することができます。

ライブラリは https://hex.pm/ に公開されていないと使えないのでしょうか?
Noです。
パスで指定、リポジトリで指定ができます。

Mix.install/2のドキュメント

Mix.install/2のドキュメントを確認してみます。

Installs and starts dependencies.
The given deps should be in the same format as defined in a regular Mix project. See mix help deps for more information. As a shortcut, an atom can be given as dependency to mean the latest version. In other words, specifying :decimal is the same as {:decimal, ">= 0.0.0"}.

mix help depsに記載されている指定方法が可能とのことです。
さっそく使ってみます。

    {:foobar, git: "https://github.com/elixir-lang/foobar.git", tag: "0.1"}
    {:foobar, path: "path/to/foobar"}

https://github.com/TORIFUKUKaiou/azure_text_to_speech

私がつくったHexです。
https://hex.pm/
に公開しようとおもってからちょうど1年くらい経ちました。

ちょうどいいのでこのHexをMix.install/2で取り込んで使ってみます。

AzureText to speech APIのラッパです。
テキストを音声データに変換してくれます。
私はこのAPIを利用して、Nervesで目覚まし時計アプリを作っていますし、使っています。

それはそうと、いい加減、明日にでもHexリリースしようとおもいます。
あ、Reqで書き直そう。
それからリリースだ〜

ちなみに私は、日本マイクロソフト賞④を受賞したことがあります。

「elixir azure 愛」で検索🔍すると動画があります。
ぜひご笑覧くださいませ。

プログラム

text_to_speech.exsを書いて楽しみます。

text_to_speech.exs
Mix.install([{:azure_text_to_speech, github: "TORIFUKUKaiou/azure_text_to_speech"}],
  force: true,
  config: [
    azure_text_to_speech: [region: "eastus", subscription_key: "秘密"]
  ]
)

locale = "ja-JP"
voice_type = "Neural"

voice =
  AzureTextToSpeech.voices_list()
  |> Enum.filter(fn %{"Locale" => l} -> l == locale end)
  |> Enum.filter(fn %{"VoiceType" => vt} -> vt == voice_type end)
  |> Enum.random()

"Hello, world. おはようございます。こんにちは。私は元気です。元気があればなんでもできる。Azureは最高です。"
|> AzureTextToSpeech.ssml(voice)
|> AzureTextToSpeech.to_speech_of_neural_voice()
|> then(&File.write("output.wav", &1))

実行はelixir text_to_speech.exsです。
実行すると、output.wavファイルができますので、その美声を再生プレイヤーで再生してお楽しみください。

subscription_keyの取得は以下を参考にしてください。


Wrapping up

この記事は、Mix.install/2関数で、https://hex.pm/ にパブリッシュされていないHexの取り込み方を示しました。
mix help depsには他にもHexの指定の仕方がいろいろ書いてあります。
ぜひご覧になってください。

やコメントは、励みになりますし、私はちょっぴりハゲています。

Enjoy Elixir
$\huge{Enjoy\ Elixir🚀}$

以上です。

  1. @kaizen_nagoya さんの「「@e99h2121 アドベントカレンダーではありますまいか Advent Calendar 2020」の改訂版ではありますまいか Advent Calendar 2022 1日目 Most Breakthrough Generator」から着想を得て、模倣いたしました。