Tech Blog
  • HOME
  • Blog
  • [Swift] Creating a sentiment analysis app with AmiVoice API and Alamofire

[Swift] Creating a sentiment analysis app with AmiVoice API and Alamofire

Published: 2022.09.30 Last updated: 2025.03.04

m-hayashi Masaki Hayashi

Hello, this is Hayashi.
I am in charge of developing iOS/watchOS apps at Advanced Media Inc.

Introduction

Recently, we added sentiment analysis feature as an optional feature to the Asynchronous HTTP speech recognition API in our AmiVoice API. This makes it possible to visualize emotions from speech, and has a wide range of use cases, including employee stress checks in call centers and personality assessments in online interviews. For more information, please see our introductory article on sentiment analysis.

Sentiment analysis now available in the Asynchronous HTTP speech recognition API


AmiVoice Cloud Platform-Tech Blog

So how can emotions extracted from audio data actually be visualized? To confirm how emotions behave, we developed an app that allows users to view sentiment analysis results and speech recognition results in time synchronization with the audio being played (see image below: the app in this article).

In a previous article, we developed a WatchOS app that uses the AmiVoice API's Asynchronous HTTP speech recognition API to test speech recognition on the Apple Watch.

I tried out AmiVoice's Asynchronous API on my Apple Watch


AmiVoice Cloud Platform-Tech Blog

In a previous article, we implemented HTTP communication using the standard framework URLSession, but this time we implemented it using a library called Alamofire, which I personally find easier to work with than URLSession.

・Want to try sentiment analysis in an iOS application

・Want to easily use the AmiVoice API with Swift

If you are interested, please read it.

Implementation

○ Development environment

  • macOS Monterey 12.5.1
  • Xcode 13.4.1
  • Swift 5.0
  • iOS 14 and later

GitHub

github.com

○ Asynchronous HTTP speech recognition API

To perform sentiment analysis in an iOS app, you must first implement the AmiVoice API's Asynchronous HTTP speech recognition API in Swift. For information on implementing the Asynchronous HTTP speech recognition API in Swift, please refer to our previous article.

I tried out AmiVoice's asynchronous API on Apple Watch – AmiVoice Techblog

① POST request for speech recognition

When using sentiment analysis with the AmiVoice API asynchronous HTTP speech recognition API, it is necessary to add sentimentAnalysis=True to the d parameter section as shown in the request image below.

POST https://acp-api-async.amivoice.com/v1/recognitions
Content-Type: multipart/form-data;boundary=some-boundary-string
--some-boundary-string
Content-Disposition: form-data; name="u" (<AppKey>) 
--some-boundary-string
Content-Disposition: form-data; name="d" 
grammarFileNames=-a-general sentimentAnalysis=True profileWords=hogehoge%20%E3%81%BB%E3%81%92%E3%81%BB%E3%81%92%E3%81%A6%E3%81%99%E3%81%A8
--some-boundary-string
Content-Disposition: form-data; name="a" 
Content-Type: application/octet-stream (Audio data) 
--some-boundary-string--

Using the request image above as a reference, a speech recognition request with the AmiVoice API can be implemented using Alamofire as follows:

let appKey = "ABCD..." 
let url = "https://acp-api-async.amivoice.com/v1/recognitions" 

let headers: HTTPHeaders = [ 
    "Content-type": "multipart/form-data" 
]

AF.upload(multipartFormData: { multipartFormData in 
    multipartFormData.append(appKey.data(using: .utf8)!, 
                             withName: "u",
                             fileName: nil,
                             mimeType: nil)
    multipartFormData.append("grammarFileNames=-a-general sentimentAnalysis=True".data(using: .utf8)!, 
                             withName: "d",
                             fileName: nil,
                             mimeType: nil)
    multipartFormData.append(audioData,
                             withName: "a",
                             fileName: "audio.wav",
                             mimeType: "application/octet-stream")
}, to: url, method: .post, headers: headers)
    .validate(statusCode: 200..<400)
    .responseData(completionHandler: { response in
        switch response.result { 
        case .success(let data): 
           // Processing if successful 
        case .failure(let error): 
           // Handling failure 
        }
    })

After making a request, please use response.result in the callback of .responseData.

② Get the job status with GET

The job status is obtained as follows:

let path = url + "/" + "Session ID"
let headers: HTTPHeaders = [ 
 "Authorization":"Bearer \(appKey)" 
]

AF.request(path, method: .get, headers: headers) 
    .validate(statusCode: 200..<400)
    .responseData { response in
        switch response.result { 
        case .success(let data): 
            // Processing if successful 
        case .failure(let error): 
            // Handling failure 
        } 
    }

The job status on the AmiVoice API side will change over time, so you will need to call the above request at any time.

When using sentiment analysis results, please use the values in sentiment_analysis of the json that can be obtained when the job status is "completed".

Supplement: About app operation

This app allows you to "play back recorded audio and check the sentiment analysis and speech recognition results over time."

When actually using this service, please try the following steps:

  ① APPKEY settings

  ② Audio recording

  ③ Display of speech recognition results and sentiment analysis results

* You can also use "character recognition" to obtain the APPKEY when setting it. Try this if you are unable to copy and paste the APPKEY.

     

That's all for how to operate the app.

Conclusion

This time, I developed an app that visualizes emotions quantified from recorded speech using the AmiVoice API's Asynchronous HTTP speech recognition API. I believe that the use cases can be further expanded by using the results of sentiment analysis in addition to the speech recognition results.

If you are interested, please give it a try.

Reference

AmiVoice API related

Asynchronous HTTP Interface | AmiVoice Cloud Platform

Sentiment analysis | AmiVoice Cloud Platform

Alamofire

GitHub – Alamofire/Alamofire: Elegant HTTP Networking in Swift

Multipart/form-data request with Alamofire – Qiita

Alamofire vs URLSession: a comparison for networking in Swift – SwiftLee

Charts (used to display sentiment analysis results)

GitHub – nubank/ios-charts: Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.

[Swift] Drawing a line graph using Charts, a charting library | DevelopersIO

Person who wrote this article

  • Masaki Hayashi

    I am developing iOS/watchOS apps using Swift/Objective-C.

Use API for Free