write()

描述

從音頻緩衝區播放音頻訊號。

語法


Audio.write(buffer, length);

參數

buffer(short):儲存音頻樣本的緩衝區。
length(int):要輸出的樣本數量。

回傳

無回傳值

範例

#include <SD.h>
#include <Audio.h>

void setup()
{
  // 輸出鮑率設定
  Serial.begin(9600);

  // 設定 SD 卡
  Serial.print("Initializing SD card...");
  if (!SD.begin()) {
    Serial.println(" failed!");
    return;
  }
  Serial.println(" done.");

  // 44100hz 立體聲 => 88200 取樣率
  // 100 毫秒的緩衝時間
  Audio.begin(88200, 100);
}

void loop()
{
  int count=0;

  // 從 SD 卡開啟音頻檔案
  File myFile = SD.open("test.wav");
  if (!myFile) {
    // 如果開啟檔案失敗,印出錯誤訊息並中止
    Serial.println("error opening test.wav");
    while (true);
  }

  const int S=1024; // 每個區塊的取樣個數
  short buffer[S];

  Serial.print("Playing");
  // 直到檔案結束
  while (myFile.available()) {
    // 從檔案讀取資料至 buffer
    myFile.read(buffer, sizeof(buffer));

    // 預備樣本
    int volume = 1023;
    Audio.prepare(buffer, S, volume);
    // 輸出緩衝區中的音頻樣本
    Audio.write(buffer, S);

    // 每一百個區塊印出一個 '.'
    count++;
    if (count == 100) {
      Serial.print(".");
      count = 0;
    }
  }
  myFile.close();

  Serial.println("End of file. Thank you for listening!");
  while (true) ;
}

函式庫參考主頁面

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.