すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:リアルタイム音声認識 - Fun-ASR/Paraformer

最終更新日:Dec 05, 2025

リアルタイム音声認識サービスは、オーディオストリームをリアルタイムで句読点付きのテキストに変換し、「話した内容がそのまま表示される」テキスト効果を実現します。マイク、会議の録音、またはローカルオーディオファイルからの音声を簡単に文字起こしできます。このサービスは、リアルタイムの会議文字起こし、ライブストリーミングの字幕、ボイスチャット、AI カスタマーサービスなどのシナリオで広く利用されています。

主な特徴

  • 中国語、英語、およびさまざまな方言を含む複数の言語のリアルタイム音声認識をサポートします。

  • カスタムホットワードをサポートし、特定の用語の認識精度を向上させます。

  • タイムスタンプ出力をサポートし、構造化された認識結果を生成します。

  • 柔軟なサンプルレートと複数のオーディオフォーマットにより、さまざまな録音環境に適応します。

  • オプションの音声アクティビティ検出 (VAD) は、無音区間を自動的にフィルタリングし、長時間の音声の処理効率を向上させます。

  • SDK と WebSocket の接続タイプにより、低遅延で安定したサービスを提供します。

利用可能状況

  • サポート対象リージョン:

    • シンガポールリージョン:シンガポールリージョンで発行された API キー が必要です。

    • 中国 (北京) リージョン:中国 (北京) リージョンで発行された API キー が必要です。

  • サポート対象モデル:

    国際(シンガポール)

    Fun-ASR:fun-asr-realtime (安定版、fun-asr-2025-11-07 に相当) および fun-asr-realtime-2025-11-07 (スナップショットバージョン)

    中国 (北京)

    • Fun-ASR:fun-asr-realtime (安定版、fun-asr-2025-11-07 に相当)、fun-asr-realtime-2025-11-07 (スナップショットバージョン)、および fun-asr-realtime-2025-09-15 (スナップショットバージョン)

    • Paraformer:paraformer-realtime-v2、paraformer-realtime-v1、paraformer-realtime-8k-v2、および paraformer-realtime-8k-v1

モデルの選択

シナリオ

推奨モデル

理由

中国語 (標準語) 認識 (会議/ライブストリーミング)

fun-asr-realtime、fun-asr-realtime-2025-11-07、paraformer-realtime-v2

複数のフォーマットに対応し、高いサンプルレートをサポート、安定した遅延。

多言語認識 (国際会議)

paraformer-realtime-v2

複数の言語をカバー。

中国語方言認識 (カスタマーサービス/行政サービス)

fun-asr-realtime-2025-11-07、paraformer-realtime-v2

複数の方言をカバー。

中国語、英語、日本語の混合認識 (授業/スピーチ)

fun-asr-realtime、fun-asr-realtime-2025-11-07

中国語、英語、日本語の認識に最適化。

低帯域幅の電話録音の文字起こし

paraformer-realtime-8k-v2

8 kHz をサポート、感情認識がデフォルトで有効。

カスタムホットワードのシナリオ (ブランド名/専門用語)

Paraformer、Fun-ASR モデルの最新バージョン

ホットワードの有効/無効を切り替え可能、設定とイテレーションが容易。

詳細については、「モデル機能の比較」をご参照ください。

はじめに

以下は API を呼び出すためのコードサンプルです。一般的なシナリオのその他のコードサンプルについては、GitHub をご参照ください。

API キーを取得し、API キーを環境変数として設定する必要があります。SDK を使用して呼び出しを行う場合は、DashScope SDK をインストールする必要もあります。

Fun-ASR

マイクからの音声を認識

リアルタイム音声認識を使用してマイクからの音声を認識し、結果を出力することで、「話した内容がそのまま表示される」テキスト効果を実現できます。

Java

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionResult;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.TargetDataLine;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        // 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を wss://dashscope.aliyuncs.com/api-ws/v1/inference に置き換えてください。
        Constants.baseWebsocketApiUrl = "wss://dashscope-intl.aliyuncs.com/api-ws/v1/inference";
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new RealtimeRecognitionTask());
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);
        System.exit(0);
    }
}

class RealtimeRecognitionTask implements Runnable {
    @Override
    public void run() {
        RecognitionParam param = RecognitionParam.builder()
                .model("fun-asr-realtime")
                // シンガポールリージョンと北京リージョンでは API キーが異なります。API キーの取得については、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください。
                // 環境変数を設定していない場合は、次の行を実際の Model Studio API キーに置き換えてください:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .format("wav")
                .sampleRate(16000)
                .build();
        Recognition recognizer = new Recognition();

        ResultCallback<RecognitionResult> callback = new ResultCallback<RecognitionResult>() {
            @Override
            public void onEvent(RecognitionResult result) {
                if (result.isSentenceEnd()) {
                    System.out.println("Final Result: " + result.getSentence().getText());
                } else {
                    System.out.println("Intermediate Result: " + result.getSentence().getText());
                }
            }

            @Override
            public void onComplete() {
                System.out.println("Recognition complete");
            }

            @Override
            public void onError(Exception e) {
                System.out.println("RecognitionCallback error: " + e.getMessage());
            }
        };
        try {
            recognizer.call(param, callback);
            // オーディオフォーマットを作成します。
            AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
            // フォーマットに基づいてデフォルトの録音デバイスをマッチングします。
            TargetDataLine targetDataLine =
                    AudioSystem.getTargetDataLine(audioFormat);
            targetDataLine.open(audioFormat);
            // 録音を開始します。
            targetDataLine.start();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            long start = System.currentTimeMillis();
            // 50 秒間録音し、リアルタイムで文字起こしを行います。
            while (System.currentTimeMillis() - start < 50000) {
                int read = targetDataLine.read(buffer.array(), 0, buffer.capacity());
                if (read > 0) {
                    buffer.limit(read);
                    // 録音したオーディオデータをストリーミング認識サービスに送信します。
                    recognizer.sendAudioFrame(buffer);
                    buffer = ByteBuffer.allocate(1024);
                    // 録音レートは制限されています。CPU 使用率が高くなるのを防ぐため、短時間スリープします。
                    Thread.sleep(20);
                }
            }
            recognizer.stop();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // タスク完了後、WebSocket 接続を閉じます。
            recognizer.getDuplexApi().close(1000, "bye");
        }

        System.out.println(
                "[Metric] requestId: "
                        + recognizer.getLastRequestId()
                        + ", first package delay ms: "
                        + recognizer.getFirstPackageDelay()
                        + ", last package delay ms: "
                        + recognizer.getLastPackageDelay());
    }
}

Python

Python サンプルを実行する前に、pip install pyaudio コマンドを実行して、サードパーティのオーディオ再生およびキャプチャライブラリをインストールしてください。

import os
import signal  # キーボードイベント処理用 (「Ctrl+C」を押して録音を終了)
import sys

import dashscope
import pyaudio
from dashscope.audio.asr import *

mic = None
stream = None

# 録音パラメーターを設定
sample_rate = 16000  # サンプリングレート (Hz)
channels = 1  # モノラルチャンネル
dtype = 'int16'  # データ型
format_pcm = 'pcm'  # オーディオデータのフォーマット
block_size = 3200  # バッファーごとのフレーム数


# リアルタイム音声認識コールバック
class Callback(RecognitionCallback):
    def on_open(self) -> None:
        global mic
        global stream
        print('RecognitionCallback open.')
        mic = pyaudio.PyAudio()
        stream = mic.open(format=pyaudio.paInt16,
                          channels=1,
                          rate=16000,
                          input=True)

    def on_close(self) -> None:
        global mic
        global stream
        print('RecognitionCallback close.')
        stream.stop_stream()
        stream.close()
        mic.terminate()
        stream = None
        mic = None

    def on_complete(self) -> None:
        print('RecognitionCallback completed.')  # 認識完了

    def on_error(self, message) -> None:
        print('RecognitionCallback task_id: ', message.request_id)
        print('RecognitionCallback error: ', message.message)
        # オーディオストリームが実行中の場合は停止して閉じる
        if 'stream' in globals() and stream.active:
            stream.stop()
            stream.close()
        # プログラムを強制終了
        sys.exit(1)

    def on_event(self, result: RecognitionResult) -> None:
        sentence = result.get_sentence()
        if 'text' in sentence:
            print('RecognitionCallback text: ', sentence['text'])
            if RecognitionResult.is_sentence_end(sentence):
                print(
                    'RecognitionCallback sentence end, request_id:%s, usage:%s'
                    % (result.get_request_id(), result.get_usage(sentence)))


def signal_handler(sig, frame):
    print('Ctrl+C pressed, stop recognition ...')
    # 認識を停止
    recognition.stop()
    print('Recognition stopped.')
    print(
        '[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
        .format(
            recognition.get_last_request_id(),
            recognition.get_first_package_delay(),
            recognition.get_last_package_delay(),
        ))
    # プログラムを強制終了
    sys.exit(0)


# main 関数
if __name__ == '__main__':
    # シンガポールリージョンと北京リージョンでは API キーが異なります。API キーの取得については、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    # 環境変数を設定していない場合は、次の行を実際の Model Studio API キーに置き換えてください:dashscope.api_key = "sk-xxx"
    dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')

    # 次はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を次のように置き換えてください:wss://dashscope.aliyuncs.com/api-ws/v1/inference
    dashscope.base_websocket_api_url='wss://dashscope-intl.aliyuncs.com/api-ws/v1/inference'

    # 認識コールバックを作成
    callback = Callback()

    # 非同期モードで認識サービスを呼び出します。モデル、フォーマット、
    # sample_rate などの認識パラメーターをカスタマイズできます
    recognition = Recognition(
        model='fun-asr-realtime',
        format=format_pcm,
        # 'pcm'、'wav'、'opus'、'speex'、'aac'、'amr'。サポートされているフォーマットはドキュメントで確認できます。
        sample_rate=sample_rate,
        # 8000、16000 をサポートします。
        semantic_punctuation_enabled=False,
        callback=callback)

    # 認識を開始
    recognition.start()

    signal.signal(signal.SIGINT, signal_handler)
    print("Press 'Ctrl+C' to stop recording and recognition...")
    # 「Ctrl+C」が押されるまでキーボードリスナーを作成

    while True:
        if stream:
            data = stream.read(3200, exception_on_overflow=False)
            recognition.send_audio_frame(data)
        else:
            break

    recognition.stop()

ローカルオーディオファイルの認識

リアルタイム音声認識を使用してローカルオーディオファイルを認識し、認識結果を出力できます。この機能は、対話、音声コマンド、音声入力、音声検索など、短い音声を伴うニアリアルタイムの音声認識シナリオに適しています。

Java

この例で使用されるオーディオファイルは asr_example.wav です。

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionResult;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class TimeUtils {
    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    public static String getTimestamp() {
        return LocalDateTime.now().format(formatter);
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        // 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を wss://dashscope.aliyuncs.com/api-ws/v1/inference に置き換えてください。
        Constants.baseWebsocketApiUrl = "wss://dashscope-intl.aliyuncs.com/api-ws/v1/inference";
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new RealtimeRecognitionTask(Paths.get(System.getProperty("user.dir"), "asr_example.wav")));
        executorService.shutdown();

        // すべてのタスクが完了するのを待つ
        executorService.awaitTermination(1, TimeUnit.MINUTES);
        System.exit(0);
    }
}

class RealtimeRecognitionTask implements Runnable {
    private Path filepath;

    public RealtimeRecognitionTask(Path filepath) {
        this.filepath = filepath;
    }

    @Override
    public void run() {
        RecognitionParam param = RecognitionParam.builder()
                .model("fun-asr-realtime")
                // シンガポールリージョンと北京リージョンでは API キーが異なります。API キーの取得については、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください。
                // 環境変数を設定していない場合は、次の行を実際の Model Studio API キーに置き換えてください:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .format("wav")
                .sampleRate(16000)
                .build();
        Recognition recognizer = new Recognition();

        String threadName = Thread.currentThread().getName();

        ResultCallback<RecognitionResult> callback = new ResultCallback<RecognitionResult>() {
            @Override
            public void onEvent(RecognitionResult message) {
                if (message.isSentenceEnd()) {

                    System.out.println(TimeUtils.getTimestamp()+" "+
                            "[process " + threadName + "] Final Result:" + message.getSentence().getText());
                } else {
                    System.out.println(TimeUtils.getTimestamp()+" "+
                            "[process " + threadName + "] Intermediate Result: " + message.getSentence().getText());
                }
            }

            @Override
            public void onComplete() {
                System.out.println(TimeUtils.getTimestamp()+" "+"[" + threadName + "] Recognition complete");
            }

            @Override
            public void onError(Exception e) {
                System.out.println(TimeUtils.getTimestamp()+" "+
                        "[" + threadName + "] RecognitionCallback error: " + e.getMessage());
            }
        };

        try {
            recognizer.call(param, callback);
            // パスをオーディオファイルのパスに置き換えてください
            System.out.println(TimeUtils.getTimestamp()+" "+"[" + threadName + "] Input file_path is: " + this.filepath);
            // ファイルを読み込み、チャンクでオーディオを送信
            FileInputStream fis = new FileInputStream(this.filepath.toFile());
            // チャンクサイズは 16 kHz サンプルレートで 1 秒に設定
            byte[] buffer = new byte[3200];
            int bytesRead;
            // ファイルのチャンクを読み込むループ
            while ((bytesRead = fis.read(buffer)) != -1) {
                ByteBuffer byteBuffer;
                // バッファーサイズより小さい可能性のある最後のチャンクを処理
                System.out.println(TimeUtils.getTimestamp()+" "+"[" + threadName + "] bytesRead: " + bytesRead);
                if (bytesRead < buffer.length) {
                    byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead);
                } else {
                    byteBuffer = ByteBuffer.wrap(buffer);
                }

                recognizer.sendAudioFrame(byteBuffer);
                buffer = new byte[3200];
                Thread.sleep(100);
            }
            System.out.println(TimeUtils.getTimestamp()+" "+LocalDateTime.now());
            recognizer.stop();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // タスク完了後、WebSocket 接続を閉じます。
            recognizer.getDuplexApi().close(1000, "bye");
        }

        System.out.println(
                "["
                        + threadName
                        + "][Metric] requestId: "
                        + recognizer.getLastRequestId()
                        + ", first package delay ms: "
                        + recognizer.getFirstPackageDelay()
                        + ", last package delay ms: "
                        + recognizer.getLastPackageDelay());
    }
}

Python

この例で使用されるオーディオファイルは asr_example.wav です。

import os
import time
import dashscope
from dashscope.audio.asr import *

# シンガポールリージョンと北京リージョンでは API キーが異なります。API キーの取得については、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# 環境変数を設定していない場合は、次の行を実際の Model Studio API キーに置き換えてください:dashscope.api_key = "sk-xxx"
dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')

# 次はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を次のように置き換えてください:wss://dashscope.aliyuncs.com/api-ws/v1/inference
dashscope.base_websocket_api_url='wss://dashscope-intl.aliyuncs.com/api-ws/v1/inference'

from datetime import datetime

def get_timestamp():
    now = datetime.now()
    formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
    return formatted_timestamp

class Callback(RecognitionCallback):
    def on_complete(self) -> None:
        print(get_timestamp() + ' Recognition completed')  # 認識完了

    def on_error(self, result: RecognitionResult) -> None:
        print('Recognition task_id: ', result.request_id)
        print('Recognition error: ', result.message)
        exit(0)

    def on_event(self, result: RecognitionResult) -> None:
        sentence = result.get_sentence()
        if 'text' in sentence:
            print(get_timestamp() + ' RecognitionCallback text: ', sentence['text'])
            if RecognitionResult.is_sentence_end(sentence):
                print(get_timestamp() + 
                    'RecognitionCallback sentence end, request_id:%s, usage:%s'
                    % (result.get_request_id(), result.get_usage(sentence)))


callback = Callback()

recognition = Recognition(model='fun-asr-realtime',
                          format='wav',
                          sample_rate=16000,
                          callback=callback)

recognition.start()

try:
    audio_data: bytes = None
    f = open("asr_example.wav", 'rb')
    if os.path.getsize("asr_example.wav"):
        while True:
            audio_data = f.read(3200)
            if not audio_data:
                break
            else:
                recognition.send_audio_frame(audio_data)
            time.sleep(0.1)
    else:
        raise Exception(
            'The supplied file was empty (zero bytes long)')
    f.close()
except Exception as e:
    raise e

recognition.stop()

print(
    '[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
    .format(
        recognition.get_last_request_id(),
        recognition.get_first_package_delay(),
        recognition.get_last_package_delay(),
    ))

Paraformer

マイクからの音声を認識

リアルタイム音声認識を使用してマイクからの音声を認識し、結果を出力することで、「話した内容がそのまま表示される」テキスト効果を実現できます。

Java

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;

import java.nio.ByteBuffer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.TargetDataLine;

public class Main {

    public static void main(String[] args) throws NoApiKeyException {
        // Flowable<ByteBuffer> を作成します。
        Flowable<ByteBuffer> audioSource = Flowable.create(emitter -> {
            new Thread(() -> {
                try {
                    // オーディオフォーマットを作成します。
                    AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
                    // フォーマットに基づいてデフォルトの録音デバイスをマッチングします。
                    TargetDataLine targetDataLine =
                            AudioSystem.getTargetDataLine(audioFormat);
                    targetDataLine.open(audioFormat);
                    // 録音を開始します。
                    targetDataLine.start();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    long start = System.currentTimeMillis();
                    // 300 秒間録音し、リアルタイムで文字起こしを行います。
                    while (System.currentTimeMillis() - start < 300000) {
                        int read = targetDataLine.read(buffer.array(), 0, buffer.capacity());
                        if (read > 0) {
                            buffer.limit(read);
                            // 録音したオーディオデータをストリーミング認識サービスに送信します。
                            emitter.onNext(buffer);
                            buffer = ByteBuffer.allocate(1024);
                            // 録音レートは制限されています。CPU 使用率が高くなるのを防ぐため、短時間スリープします。
                            Thread.sleep(20);
                        }
                    }
                    // 文字起こしの終了を通知します。
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }).start();
        },
        BackpressureStrategy.BUFFER);

        // Recognizer を作成します。
        Recognition recognizer = new Recognition();
        // RecognitionParam を作成し、作成した Flowable<ByteBuffer> を audioFrames パラメーターに渡します。
        RecognitionParam param = RecognitionParam.builder()
            .model("paraformer-realtime-v2")
            .format("pcm")
            .sampleRate(16000)
            // API キーを環境変数として設定していない場合は、次の行のコメントを解除し、apiKey をご自身の API キーに置き換えてください。
            // .apiKey("apikey")
            .build();

        // ストリーミングモードでインターフェイスを呼び出します。
        recognizer.streamCall(param, audioSource)
            // Flowable の subscribe メソッドを呼び出して結果をサブスクライブします。
            .blockingForEach(
                result -> {
                    // 最終結果を出力します。
                    if (result.isSentenceEnd()) {
                        System.out.println("Fix:" + result.getSentence().getText());
                    } else {
                        System.out.println("Result:" + result.getSentence().getText());
                    }
                });
        System.exit(0);
    }
}

Python

Python サンプルを実行する前に、pip install pyaudio コマンドを実行して、サードパーティのオーディオ再生およびキャプチャライブラリをインストールしてください。

import pyaudio
from dashscope.audio.asr import (Recognition, RecognitionCallback,
                                 RecognitionResult)

# API キーを環境変数として設定していない場合は、次の行のコメントを解除し、apiKey をご自身の API キーに置き換えてください。
# import dashscope
# dashscope.api_key = "apiKey"

mic = None
stream = None


class Callback(RecognitionCallback):
    def on_open(self) -> None:
        global mic
        global stream
        print('RecognitionCallback open.')
        mic = pyaudio.PyAudio()
        stream = mic.open(format=pyaudio.paInt16,
                          channels=1,
                          rate=16000,
                          input=True)

    def on_close(self) -> None:
        global mic
        global stream
        print('RecognitionCallback close.')
        stream.stop_stream()
        stream.close()
        mic.terminate()
        stream = None
        mic = None

    def on_event(self, result: RecognitionResult) -> None:
        print('RecognitionCallback sentence: ', result.get_sentence())


callback = Callback()
recognition = Recognition(model='paraformer-realtime-v2',
                          format='pcm',
                          sample_rate=16000,
                          callback=callback)
recognition.start()

while True:
    if stream:
        data = stream.read(3200, exception_on_overflow=False)
        recognition.send_audio_frame(data)
    else:
        break

recognition.stop()

ローカルオーディオファイルの認識

リアルタイム音声認識を使用してローカルオーディオファイルを認識し、認識結果を出力できます。この機能は、対話、音声コマンド、音声入力、音声検索など、短い音声を伴うニアリアルタイムの音声認識シナリオに適しています。

Java

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Main {
    public static void main(String[] args) {
        // ファイルダウンロード部分は無視して、直接ローカルファイルを使用して API を呼び出して認識できます。
        String exampleWavUrl =
                "https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female2.wav";
        try {
            InputStream in = new URL(exampleWavUrl).openStream();
            Files.copy(in, Paths.get("asr_example.wav"), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            System.out.println("error: " + e);
            System.exit(1);
        }

        // Recognition インスタンスを作成します。
        Recognition recognizer = new Recognition();
        // RecognitionParam を作成します。
        RecognitionParam param =
                RecognitionParam.builder()
                        // API キーを環境変数として設定していない場合は、次の行のコメントを解除し、apiKey をご自身の API キーに置き換えてください。
                        // .apiKey("apikey")
                        .model("paraformer-realtime-v2")
                        .format("wav")
                        .sampleRate(16000)
                        // "language_hints" は paraformer-v2 および paraformer-realtime-v2 モデルでのみサポートされています。
                        .parameter("language_hints", new String[]{"zh", "en"})
                        .build();

        try {
            System.out.println("Recognition result: " + recognizer.call(param, new File("asr_example.wav")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}

Python

import requests
from http import HTTPStatus
from dashscope.audio.asr import Recognition

# API キーを環境変数として設定していない場合は、次の行のコメントを解除し、apiKey をご自身の API キーに置き換えてください。
# import dashscope
# dashscope.api_key = "apiKey"

# URL からファイルをダウンロードするコードは無視して、直接ローカルファイルを使用して認識できます。
r = requests.get(
    'https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female2.wav'
)
with open('asr_example.wav', 'wb') as f:
    f.write(r.content)

recognition = Recognition(model='paraformer-realtime-v2',
                          format='wav',
                          sample_rate=16000,
                          # "language_hints" は paraformer-v2 および paraformer-realtime-v2 モデルでのみサポートされています。
                          language_hints=['zh', 'en'],
                          callback=None)
result = recognition.call('asr_example.wav')
if result.status_code == HTTPStatus.OK:
    print('Recognition result:')
    print(result.get_sentence())
else:
    print('Error: ', result.message)

本番環境に適用

認識パフォーマンスの向上

  • 正しいサンプルレートのモデルを選択する:8 kHz の電話音声には、音声を 16 kHz にアップサンプリングして認識するのではなく、直接 8 kHz モデルを使用します。この方法により、情報の歪みを避け、より良い結果が得られます。

  • ホットワード機能を使用する:独自の固有名詞、人名、ブランド名など、ビジネス固有の用語については、ホットワードを設定することで認識精度を大幅に向上させることができます。詳細については、「ホットワードのカスタマイズ - Paraformer/Fun-ASR」をご参照ください。

  • 入力音声の品質を最適化する:可能な限り高品質のマイクを使用し、S/N 比が高く、エコーのない録音環境を確保してください。アプリケーション層では、ノイズ除去 (例:RNNoise) やアコースティックエコーキャンセレーション (AEC) などのアルゴリズムを統合して音声を前処理し、よりクリーンな信号を取得できます。

  • 認識言語を指定する:Paraformer-v2 のように複数の言語をサポートするモデルの場合、API 呼び出し時に事前に音声の言語を特定できる場合 (例えば、Language_hints パラメーターを使用して言語を ['zh','en'] と指定する)、モデルの収束を助け、発音が似ている言語間の混同を避けることで、精度を向上させることができます。

  • フィラー (言い淀み) を除去する:Paraformer モデルでは、disfluency_removal_enabled パラメーターを設定することでフィラー除去機能を有効にできます。これにより、よりフォーマルで読みやすいテキスト結果が生成されます。

フォールトトレランスポリシーの設定

  • クライアントの再接続:クライアントは、ネットワークジッターに対処するために自動再接続メカニズムを実装する必要があります。Python SDK の場合は、次の提案を検討してください:

    1. 例外をキャッチする:Callback クラスに on_error メソッドを実装します。dashscope SDK は、ネットワークエラーやその他の問題が発生したときにこのメソッドを呼び出します。

    2. ステータス通知:on_error がトリガーされたら、再接続シグナルを設定します。Python では、スレッドセーフなフラグである threading.Event を使用できます。

    3. 再接続ループ:メインロジックを for ループでラップして、例えば 3 回のリトライを許可します。再接続シグナルが検出されると、現在の認識プロセスが中断され、リソースがクリーンアップされ、短い遅延の後、ループが再開して新しい接続を作成します。

  • 切断を防ぐためのハートビートの設定:サーバーとの持続的接続を維持するために、heartbeat パラメーターを true に設定します。これにより、音声に長時間の無音期間があっても、サーバーへの接続が中断されないようにします。

  • レート制限:モデル API を呼び出す際は、モデルのレート制限に注意してください。

API リファレンス

モデル機能の比較

機能

fun-asr-realtime, fun-asr-realtime-2025-11-07

fun-asr-realtime-2025-09-15

paraformer-realtime-v2

paraformer-realtime-v1

paraformer-realtime-8k-v2

paraformer-realtime-8k-v1

リージョン

シンガポール、中国 (北京)

中国 (北京)

主要なシナリオ

ライブ動画配信、会議、3か国語教育など

ライブ動画配信、会議、2か国語教育など

長時間音声ストリーム認識 (会議、ライブ配信)

電話カスタマーサービスなど

対応言語

中国語 (北京語、広東語、呉語、閩南語、客家語、贛語、湘語、晋語、および中原、西南、冀魯、江淮、蘭銀、膠遼、東北、北京、香港/台湾などの方言。河南省、陝西省、湖北省、四川省、重慶市、雲南省、貴州省、広東省、広西チワン族自治区、河北省、天津市、山東省、安徽省、南京市、江蘇省、杭州市、甘粛省、寧夏回族自治区を含む)、英語、日本語

中国語 (北京語)、英語

中国語 (北京語、広東語、呉語、閩南語、東北方言、甘粛方言、貴州方言、河南方言、湖北方言、湖南方言、寧夏方言、山西方言、陝西方言、山東方言、四川方言、天津方言、江西方言、雲南方言、上海語)、英語、日本語、韓国語、ドイツ語、フランス語、ロシア語

中国語 (北京語)

対応オーディオフォーマット

pcm、wav、mp3、opus、speex、aac、amr

サンプルレート

16 kHz

任意のサンプルレート

16 kHz

8 kHz

チャンネル

モノラル

入力フォーマット

バイナリ音声ストリーム

音声サイズ/時間

無制限

感情認識

非対応

対応 デフォルトで有効、無効化可能

非対応

センシティブワードフィルタリング

非対応

話者分離

非対応

フィラーワードフィルタリング

対応 デフォルトで無効、有効化可能

タイムスタンプ

対応 常時有効

句読点予測

対応 常時有効

対応 デフォルトで有効、無効化可能

対応 常時有効

対応 デフォルトで有効、無効化可能

対応 常時有効

ホットワード

対応 設定可能

ITN

対応 常時有効

VAD

対応 常時有効

レート制限 (RPS)

20

接続方法

Java/Python SDK、WebSocket API

価格

インターナショナル (シンガポール):$0.00009/秒

中国 (北京):$0.000047/秒

中国 (北京):$0.000047/秒

中国 (北京):$0.000012/秒