2023-09-05

import React, {useState, useRef}  from 'react';
import { View, StyleSheet, Text, TouchableOpacity, Dimensions, ScrollView } from 'react-native';
import * as Speech from 'expo-speech';
const windowWidth = Dimensions.get('window').width;
const sliderLeft = 36+16+50;
const sliderWidth = windowWidth - 2*sliderLeft+50;
const initRateValue = 2;
const initPitchValue = 1.0;
export default function App() {
  const [voiceList, setVoiceList] = useState([]);
  const [voiceId, setVoiceId] = useState("");
  const rate = useRef(initRateValue);
  const pitch = useRef(initPitchValue);
  Speech.getAvailableVoicesAsync().then(r => {
    setVoiceList(([r.filter(i => i.language == "en-US"), r.filter(i => i.language == "en-GB")]) || []);
    setVoiceId(r.filter(i => i.language == "en-US")[0].identifier);
  })
  const speak = () => {
    const thingToSay = '1';
    Speech.speak(thingToSay);
  };

  const selectVoice = (identifier) => {
    setVoiceId(identifier);
  }

  const settingAction = () => {
    
  }

  return (
    <View style={styles.container}>
      <Slider style={{marginHorizontal: 16, marginTop: 24}}
        name="速度:" 
        value={initRateValue} 
        valueChanged={(i) => {rate.current = i}}/>
      <Slider style={{marginHorizontal: 16, marginTop: 20}} 
        name="音调:"
        value={initPitchValue} 
        valueChanged={(i) => {pitch.current = i} }/>
      
      <ScrollView style={{flex: 1, backgroundColor: 'red', marginTop: 10}}>
        {voiceList.map((list, i) =>
          <View style={{backgroundColor: '#f5f6f7'}}>
            <Text style={{lineHeight: 40, marginLeft: 16}} key={i}>{i == 0 ? "美音": "英音"}</Text>
            {list.map((voice, index) => 
              <TouchableOpacity onPress={() => selectVoice(voice.identifier)} activeOpacity={0.6} style={{backgroundColor: '#fff'}} key={`${i}_${index}`}>
                <View style={{ flexDirection: 'row', alignItems: 'center', marginHorizontal: 16}}>
                  <Text style={{lineHeight: 54, fontSize: 16}}>{voice.name}</Text>
                  <View style={{flex: 1}}/>
                  <Text style={{fontSize: 14, color: '#67676a'}}>{voice.quality == "Default" ? "标准音质": "高级音质"}</Text>
                  <View style={{width: 10, height: 10, borderRadius: 5, backgroundColor: voiceId === voice.identifier ? 'red': '#eee', marginLeft: 15 }}/>
                </View>
                <View style={{height: 1, backgroundColor: '#ececef'}}/>
              </TouchableOpacity>)}
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
  },
});

const Slider = ({style, name, value=1.1, valueChanged}) => {
  const [_value, setValue] = useState(value);
  const onPress = (event) => {
    var v = ((event.nativeEvent.pageX - sliderLeft) / sliderWidth * 1.5 + 0.5).toFixed(1);
    v = Math.max(0.5, Math.min(v, 2.0));
    setValue(v);
    valueChanged(0.8);
  }
  return <View style={style}>
    <View style={{height: 40, flexDirection: 'row', alignItems: 'center'}}>
    <Text style={{lineHeight: 40, width: 50}}>{name}</Text>
      <Text style={{lineHeight: 40, width: 31}}>0.5</Text>
      <TouchableOpacity onPress={(e) =>onPress(e)} activeOpacity={1} style={{flex: 1, height: 40, flexDirection: 'row', paddingHorizontal: 5}}>
        <View style={{position: "absolute", left:5, right: 15, top: 19.5, height: 1, backgroundColor: '#e1e2e4'}}/>
        <View style={{flex:(_value-0.5)/(1.5)}}/>
        <View style={{ paddingVertical: 5, width: 30, height: 40, marginLeft: -15}}>
          <View style={{ backgroundColor: 'white', alignItems: 'center', width: 30, height: 30,
            shadowColor: "#000", shadowOpacity: 0.13, shadowRadius: 8, borderRadius: 15, elevation: 5}}>
            <Text style={{color: "#6a6a67", fontSize: 11, fontWeight: 700, lineHeight: 30}}>{_value}</Text>
          </View>
        </View>
      </TouchableOpacity>
      <Text style={{lineHeight: 40, width: 21, textAlign: 'end'}}>2.0</Text>
    </View>
  </View>
}
class AudioArticlePlay {
    const addListener = ({ onNext, onSpeakingChanged, didFinished }) => {
        this._didFinished = didFinished;
        this._onNext = onNext;
        this._onSpeakingChanged = onSpeakingChanged;
    }
    const removeListener = () => {
        this._didFinished = null;
        this._onNext = null;
        this._onSpeakingChanged = null;
    }
    
    set isSpeaking(value) {
        this._isSpeaking = value;
        if (this._onSpeakingChanged) {
            this._onSpeakingChanged(value);
        }
    }
    get isSpeaking() {
        return this._isSpeaking;
    }
    get location() {
        return this._location;
    }
    
    const releasDatas = () => {
        this.removeListener();
        this._article = null;
        this._title = null;
        this._id = null;
        this._sentences = null;
        this._location = null;
        this._isSpeaking = false;
    }
    
    const setNewDatas = ({article, title, id}) => {
        this._article = article;
        this._title = title;
        this._id = id;
        this._sentences = getSentences(article);
        this._location = {section: -1, item: 0};
    }
    
    const playSentence = () => {
        const location = this._location;
        var sentence = "";
        if (location.section == -1) {
            sentence = this._title;
        } else {
            sentence = this._sentences[location.section][location.item];
        }
        Speech.speak(sentence, {
            voice: this._voice.identifier,
            language: this._voice.language || "en_US",
            rate: (this._voice.rate > 0.1) ? this._voice.rate: 1.0,
            pitch: (this._voice.pitch> 0.1) ? this._voice.pitch: 1.0,
            onDone: () => {
                let next = this.getNextLocation();
                if (next != null) {
                    if (this._id) {
                        this._location = next;
                        this.playSentence();
                    } else {
                        this.isSpeaking = false;
                    }
                    if (this._onNext) {
                        this._onNext(next);
                    }
                } else {
                    if (this._didFinished) {
                        this._didFinished();
                    }
                    this.releasDatas();
                }
            },
            onError: () => {
                this.isSpeaking = false;
            },
        })
    }
    const newPlaySentence = async (l) => {
        try {
            const location = l || this._location;
            this._location = location;
            this._voice = JSON.parse(await AsyncStorage.getItem('Speech_Setting'));
            await Speech.stop();
            if (this._onNext) {
                this._onNext(location);
            }
            this.playSentence();
            this.isSpeaking = true;
        } catch (e) {
            this.isSpeaking = false;
        }
    }
    
    const stop = async () => {
        await Speech.stop();
        this.isSpeaking = false;
    }
    
    const getNextLocation = () => {
        return null;
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • 今天看了一个大佬的分享,了解了如何判断一个岗位是否适合,做了总结,给别人做了分享主要是要直接找到这个岗位人去问下面...
    探索践行者阅读 25评论 0 0
  • 两性篇章:双向奔赴才能赢 在人生的旅途中,爱情是最美好的一段路程。在爱情中,双方都需要付出真心、共同经营,才能让爱...
    森林走心篇章阅读 37评论 0 0
  • 主题教育风正劲 乘势而上开新局 当前,全党正深入开展学习贯彻习近平新时代中国特色社会主...
    wen11阅读 45评论 0 0
  • 孩子不带手机,家长群里炸锅了 开学第一周,学校不让带手机,如果特殊情况需要,提前打个申请,家长签字,但手机带到学校...
    花阡陌2022阅读 65评论 0 0
  • 生活好似又重新步入了一种方式。比之前慢了下来。不是说事物变少了,而是心态上多一些从容不迫了。这样的状态是好的。 昨...
    浪矢杂货店阅读 272评论 2 10