如何通过智能手机中多个内置扬声器中的特定扬声器播放音乐?

How can I play music through a specific speaker among the multiple built-in speakers in a smartphone?

提问人:Jihwan Lee 提问时间:11/17/2023 最后编辑:James ZJihwan Lee 更新时间:11/17/2023 访问量:12

问:

我的智能手机是 Galaxy S22,主扬声器位于底部,副扬声器位于顶部。 通常,听音乐时,它通过主扬声器播放。

但是,当我使用使用上述代码创建的应用程序播放音乐时,它使用副扬声器。如何解决此问题?无论是通过修改代码还是更改智能手机设置。

我已经探索了与 AudioTrack 相关的各种问题,但没有找到解决方案。

package com.example.heartouch.playback

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.os.Environment
import java.io.File
import java.io.FileInputStream
import java.util.Date
import java.util.concurrent.Executors

class AudioPlayer(private val context: Context) {

    private val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
    private var audioTrack: AudioTrack? = null

    fun start() {

        val executor = Executors.newSingleThreadExecutor()

        executor.execute {
            val inputFileName = "play.wav"
            val wavfile = File(outputDir, inputFileName)


            if (wavfile.exists()) {
                val audioData = ByteArray(wavfile.length().toInt())
                val fileInputStream = FileInputStream(wavfile)
                fileInputStream.read(audioData)
                fileInputStream.close()

                val sampleRate = 48000
                val channelConfig = AudioFormat.CHANNEL_OUT_MONO
                val audioFormat = AudioFormat.ENCODING_PCM_16BIT
                val bufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat)

                audioTrack = AudioTrack(
                    AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                        .build(),
                    AudioFormat.Builder()
                        .setSampleRate(sampleRate)
                        .setEncoding(audioFormat)
                        .setChannelMask(channelConfig)
                        .build(),
                    bufferSize,
                    AudioTrack.MODE_STREAM,
                    AudioManager.AUDIO_SESSION_ID_GENERATE
                )

                audioTrack?.play()

                audioTrack?.write(audioData, 0, audioData.size)
            } else {
                // Handle case where file doesn't exist
            }
        }
    }

    fun stop() {
        audioTrack?.stop()
        audioTrack?.release()
    }
}
Android 音频 播放 AudioTrack 扬声器

评论


答: 暂无答案